【问题标题】:SimpleDateFormat returns wrong date value during parseSimpleDateFormat 在解析期间返回错误的日期值
【发布时间】:2014-02-13 19:42:46
【问题描述】:

我面临一个问题:我想获得 GMT TimeZone 的当前时间。 我正在使用以下代码,如下所示:

  TimeZone timeZoneGmt = TimeZone.getTimeZone("GMT");
  long gmtCurrentTime = getCurrentTimeInSpecificTimeZone(timeZoneGmt);

    public static long getCurrentTimeInSpecificTimeZone(TimeZone timeZone) {
    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(timeZone);
    long finalValue = 0;
    SimpleDateFormat sdf = new SimpleDateFormat(
            "MMM dd yyyy hh:mm:ss:SSSaaa");

    sdf.setTimeZone(timeZone);

    Date finalDate = null;

    String date = sdf.format(cal.getTime());
    try {
        finalDate = sdf.parse(date);

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    finalValue = finalDate.getTime();
    return finalValue;
}

如上所示,上述方法 格式化时
String date = sdf.format(cal.getTime()); 我在格林威治标准时间得到正确的当前时间,但正如我通过以下代码解析的那样:

finalDate=sdf.parse(date);

日期已从当前 GMT 时间更改为 2013 年 IST 15:35:16,这是我系统的当前时间。

我也以另一种方式尝试使用日历:

TimeZone timeZoneGmt=TimeZone.get("GMT"); 
Calendar calGmt = Calendar.getInstance(); 
calGmt.setTimeZone(timeZoneGmt); 
long finalGmtValue = 0; 
finalGmtValue = calGmt.getTimeInMillis(); 
System.out.println("Date......" + calGmt.getTime()); 

但仍将日期作为我系统的当前时间 Thu Jan 23 15:58:16 IST 2014 未获得 GMT 当前时间。

【问题讨论】:

    标签: java android timezone simpledateformat


    【解决方案1】:

    您误解了Date 的工作原理。 Date 没有时区 - 如果您使用 Date.toString(),您将始终看到默认时区。 Date 中的 long 值纯粹是自 Unix 纪元以来的毫秒数:它没有任何时区或日历系统的概念。

    如果您想表示特定时区和日历中的日期和时间,请改用Calendar - 但要获取“当前日期和时间”,您可以只使用System.currentTimeMillis(),这又是与系统时区无关。

    此外,即使您确实想要进行这样的操作,也不应该使用字符串转换。您在概念上并没有执行任何字符串转换,那么为什么要引入它们呢?

    如果您的目标是在特定时区显示(作为字符串)当前日期和时间,您应该使用类似的内容:

    Date date = new Date(); // This will use the current time
    SimpleDateFormat format = new SimpleDateFormat(...); // Pattern and locale
    format.setTimeZone(zone); // The zone you want to display in
    
    String formattedText = format.format(date);
    

    使用日期和时间 API(尤其是 Java Calendar/Date API 等糟糕的 API)时,非常准确了解系统中每个值所代表的含义。 p>

    【讨论】:

    • 我想要一个特定时区的当前日期为long。这就是原因,我正在解析日期字符串。
    • @user1862243:您期望long 的值是多少?因为正如我所说,long 相对于 Java 中的日期/时间值的 正常 含义是“自 Unix 纪元以来的毫秒数”,它没有概念时区。你打算用这个值做什么?
    • @user1862243:将您的尝试编辑到您的问题中,而不是将它们添加为 cmets,但我认为您从根本上误解了您正在使用的数据类型。请在您的问题中包括您之后打算使用long 做什么。
    • @user1862243:正如我 5 分钟前所说,将您的代码编辑到问题中...但我认为您并没有真正彻底阅读我的答案。我已经解释了为什么你会得到这个结果 - Date.toString() 总是使用当前时区。时区不是Date 的一部分。我不确定我还能说多少其他方式...
    • @user1862243:这仍然留下了您打算用long 做什么的问题——实际上,您首先要解决什么更大的问题。我强烈怀疑你让你的生活变得比它需要的复杂得多。您是否已完全阅读我的答案并现在理解它?
    猜你喜欢
    • 1970-01-01
    • 2013-04-13
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多