【问题标题】:Convert Java Date into another Time as Date format将 Java 日期转换为另一种时间作为日期格式
【发布时间】:2013-04-15 10:12:17
【问题描述】:

我想将日期转换为“独立时间”。具体来说:“亚洲/加尔各答”。

代码:

// TODO Auto-generated method stub
Date date=new Date();
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));

String dateString=simpleDateFormat.format(date);

System.out.println("Currect Date : " + dateString);
// This is returning a string and I want a date.

System.out.println("Wrong Output : "+simpleDateFormat.parse(dateString)); 
//This returns a Date but has incorrect result.

这是上面代码的输出:

Correct Date : 2013-04-15 15:40:04
Wrong Output : Mon Apr 15 03:10:04 MST 2013

我想要 DATE,而不是字符串,但是当我检索日期时,时间是 3:10,当我得到字符串时,我得到 15:40:04。为什么这些不一样?

【问题讨论】:

  • 只是为了添加到其他人... Date 对象只代表一个时间点并且包含 no TZ 知识,即使您可能使用 SimpleDateFormat 对象创建了它 是知道TZ。每当您将日期转换为其字符串表示时,必须使用 TZ 以了解应如何显示它。由于 Date 不知道 TZ,当您像隐式那样调用 date.toString() 时,它别无选择,只能假设您的意思是 default TZ。您必须使用知道 TZ 的 SDF 对其进行格式化,而不是依赖 Date 的 toString() 方法。

标签: java timezone date-conversion


【解决方案1】:

parse() 解析日期文本并构造一个 long 值的 Date 对象。 parse() javadoc 说

The TimeZone value may be overwritten, depending on the given pattern and 
the time zone value in text. Any TimeZone value that has previously been 
set by a call to setTimeZone may need to be restored for further operations.

您的解析 Date 对象是通过调用在 MST 时区打印的 Date 上的 toString() 来打印的。如果您将其从 MST 转换为 IST,那么您将获得您所期望的时间戳。所以,你的输出是正确的。您需要做的就是使用正确的时区格式化并打印您的长日期值。

【讨论】:

    【解决方案2】:

    Parse 会返回一个 DateObject,所以调用:

    System.out.println("Wrong Output : "+simpleDateFormat.parse(dateString));
    

    有点类似于:

    Date d1 = simpleDateFormat.parse(dateString);
    System.out.println("Wrong Output : "+d1.toString());
    

    请记住,解析日期只是解析字符串以生成日期对象,如果您想以某种格式显示它,请使用该日期对象并在其上调用 sdf.format。 例如

     String dateStringOut=simpleDateFormat.format(d1);
     System.out.println("Output : "+dateStringOut);
    

    【讨论】:

      【解决方案3】:

      Date 不包含任何格式。它只是一个Date。因此,您不能在不同的输出格式之间转换您的 Date 对象。一旦有了日期,就无需尝试将其转换为不同的格式。当您使用SimpleDateFormat 将其转换为String 时,将决定如何格式化它。因此,一旦您解析了您的 Date,只需保留它,直到您需要对其进行格式化以进行输出。

      【讨论】:

      • 当日期存储到数据库中时,我不会存储到独立时区。
      • 如果dateString 已经生成了正确的格式,那么问题出在哪里?
      • 当我解析它时返回字符串,但随后该字符串不会转换为印度时间的日期。
      【解决方案4】:

      使用 DateFormat 类的静态函数 getDateTimeInstance(int dateStyle,int timeStyle)。 有关详细信息,请参阅 DateFormat 类。它可能会帮助你。

      【讨论】:

        猜你喜欢
        • 2022-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-27
        相关资源
        最近更新 更多