【问题标题】:Parsing date always returning 01 Jan 1970解析日期总是返回 1970 年 1 月 1 日
【发布时间】:2020-06-18 06:31:25
【问题描述】:

我从 UTC 的服务器获取日期时间,所以我需要将其转换为本地时间,并需要以长格式存储在 db 中。

但是每当我收到时间时,我都会将其解析为"yyyy-MM-dd'T'HH:mm:ss.SSS",然后将其转换为long 并将其存储在表中。但是当我尝试获取时,我总是得到01 Jan 1970

这是我的代码:

这是我从服务器获取的格式:"tourCreationDateTime":"2020-03-04T07:12:52.215+0000"

// insert tour details
Tour tour = new Tour();
if (tourId > 0) {
     tour.setId(tourId);
}
tour.setStatus(Constants.TOUR_STATUS_OPEN);
tour.setTourNumber(tourResponseDetails.getTourId());
tour.setCreatedDateTime(DateUtils.getFormattedDate(tourResponseDetails.getTourCreationDateTime(), DateUtils.DATE_FORMAT_DB));
tourDao().insertTour(tour);

这是我的日期格式:

public static final String DATE_FORMAT_DB = "yyyy-MM-dd\'T\'HH:mm:ss.SSS";    

这里是getFormattedDate 方法:

 public static long getFormattedDate(String dateString, String format){
    if(!TextUtils.isEmpty(dateString)){
        return 0L;
    }

    try {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, Locale.US);
        Date date = simpleDateFormat.parse(dateString);
        return date.getTime();

    } catch (ParseException e) {
        e.printStackTrace();
    }
    return 0L;
}

我不知道出了什么问题。任何参考都会非常好。

【问题讨论】:

  • 我建议你不要使用SimpleDateFormatDate。这些类设计不良且过时,尤其是前者,尤其是出了名的麻烦。而是使用java.time, the modern Java date and time API:return LocalDateTime.parse(dateString) .atZone(ZoneId.systemDefault()) .toInstant() .toEpochMilli();。或者如果字符串是 UTC:return LocalDateTime.parse(dateString) .atZone(ZoneOffset.UTC) .toInstant() .toEpochMilli();.
  • 你的调试器去度假了吗? :-) 投票结束是一个简单的错字。

标签: android datetime simpledateformat utc


【解决方案1】:
if(!TextUtils.isEmpty(dateString)){
    return 0L;
} 

0L 是 1970 年 1 月 1 日。
这里的错误 - if(!TextUtils.isEmpty(dateString)).
你确定它应该包含!//感叹号

【讨论】:

  • 愚蠢的错误:-)。我正试图从最后 30 分钟找出根本原因。现在需要回家了:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-07
  • 1970-01-01
  • 2021-11-24
相关资源
最近更新 更多