【问题标题】:Wrong date while using date.setTime() with date/time format by JSON data [duplicate]使用 JSON 数据的日期/时间格式的 date.setTime() 时日期错误 [重复]
【发布时间】:2012-08-01 05:38:57
【问题描述】:

我从 http://earthquake.usgs.gov/earthquakes/feed/geojson/all/hour

这里引用数据:

"properties":{
    "mag":0.5,
    "place":"123km NNW of Talkeetna, Alaska",
    "time":1343795877,
    "tz":-480,
    "url":"/earthquakes/eventpage/ak10523664",
    "felt":null,
    "cdi":null,
    "mmi":null,
    "alert":null,
    "status":"AUTOMATIC",
    "tsunami":null,
    "sig":"4",
    "net":"ak",
    "code":"10523664",
    "ids":",ak10523664,",
    "sources":",ak,",
    "types":",general-link,general-link,geoserve,nearby-cities,origin,"
},

但是当我使用时:

Date date1 = new Date();
date1.setTime("1343795877"); 

结果是:1970 年 1 月 16 日星期五 13:16:35 GMT+00:00 但正确的日期是 2012 年 8 月 1 日星期三 04:37:57 UTC(来自同一网站的 CSV 版本)

我怎样才能得到正确的时间??

【问题讨论】:

  • 更改时区对您没有帮助.. 那怎么可能.. 只是认为时区只有小时而不是年份的差异:P
  • @Abhishekbhutra Hay,我想这取决于你住在哪里 ;) - 好点,抱歉 :(

标签: java datetime-format android-date


【解决方案1】:

数字“1343795877”是unix time - 自 1970 年以来经过的时间(以秒为单位)。

您需要将它乘以 1000,因为它是以 为单位的时间,而 Date 构造函数需要毫秒。所以这会变魔术:

Date d = new Date(1343795877*1000);

您可以使用在线UNIX to Date converter查看。

请记住,UNIX 时间采用 UTC,它不会模仿用户时区 - 因此您需要应用您的时区。

我建议你使用JodaTime,它真的很方便。

这是一个转换的例子:

DateTime dt = new DateTime(1343795877*1000);
dt.withZone(DateTimeZone.forID("UTC"));

编辑:

DateTimeFormatter formatter = 
    DateTimeFormat.forPattern("dd-MM-yyyy HH:mm:ss, SSS [z]");
formatter.print(dt);

【讨论】:

  • 如何去掉“T”和“.000Z”??
  • 您需要使用适当的时区并应用格式化程序(请参阅我的编辑)
【解决方案2】:

首先你的语法是错误的。日期没有date.setTime(String) 等方法。它的date.setTime(Long) 需要milliseconds as argument。你得到的是seconds,所以只需将它乘以 1000 即可得到正确的日期。所以你的解决方案是date1.setTime(1343795877000L);

【讨论】:

    【解决方案3】:

    看这里很简单:

    new Date(epochTime * epochFormat) // '1343795877' this time format is known as epoch time
    

    epochTime 是 long 类型的时间,例如。 1343795877L
    epochFormat1000 如果 epochTime 内,否则 1 如果在 >毫秒

    在你的情况下是 所以乘以 1000

    我认为您还应该使用SimpleDateFormatter格式化您的日期:

    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE dd-MMM-yy", Locale.ENGLISH); // date format and locale you want to use
    dateFormat.setTimeZone("Asia/Kolkata"); // can have your time zone
    String date = dateFormat.format(new Date(epochTime * epochFormat));
    

    日期格式here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 2013-12-16
      • 2014-10-06
      • 1970-01-01
      • 2017-10-12
      相关资源
      最近更新 更多