【问题标题】:how to get the number of seconds passed since 1970 for a date value?如何获取日期值自 1970 年以来经过的秒数?
【发布时间】:2011-07-22 05:22:39
【问题描述】:

我需要一个 android 应用程序,我需要在其中将当前日期转换为 自 1970 年以来经过的秒数

我目前正在做的就是这个。

Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
cal.set(currentDate.get(Calendar.YEAR), month, currentDate.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
long timesince1970 = cal.getTime().getTime();

另一个问题是我的应用程序需要在德国运行。因此需要将时间转换为他们的时区,然后将其转换为自 1970 年以来的秒数。

以上没有给我正确的结果。

【问题讨论】:

    标签: android


    【解决方案1】:

    System.currentTimeMillis() 为您提供自 Unix 纪元(1970 年 1 月 1 日 00:00:00 UTC)以来的毫秒数。

    除以 1000 得到秒数。

    【讨论】:

    • 既然它来自System,如果用户更改日期,currentTimeMillis() 是否会有所不同?
    • @CliffBurton:是的,确实如此。 Android 手机通常设置为自动同步时间,但返回的日期可能是错误的。如果您需要准确的时间,您通常需要进行某种在线检查。 (注:由于返回时间为UTC,不受夏令时或时区影响,除非出错)
    【解决方案2】:
    //long currentTimeMillis ()-Returns the current time in milliseconds. 
    long millis = System.currentTimeMillis();
    
    //Divide millis by 1000 to get the number of seconds.
    long seconds = millis / 1000;
    

    【讨论】:

    • 你应该解释为什么你的代码回答了这个问题。
    猜你喜欢
    • 2011-08-06
    • 2019-07-10
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    相关资源
    最近更新 更多