【问题标题】:Convert date string to readable date format [duplicate]将日期字符串转换为可读的日期格式[重复]
【发布时间】:2016-02-11 04:38:19
【问题描述】:

我收到的日期为“1279340983”,因此我想转换为可读格式,如 2010-07-17。我尝试使用以下代码

String createdTime = "1279340983";
Date date1 = new Date(Long.parseLong(createdTime));
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf1.format(date1));

但它返回1970-01-16作为输出。当尝试使用在线工具时,它显示 Sat, 17 Jul 2010 04:29:43 GMT 知道为什么这段代码没有显示预期的输出吗?

【问题讨论】:

  • 2010-07-2010 怎么可能?你的格式是yyyy-MM-dd
  • 对不起,我编辑的错字
  • 只是为了验证,你的数字是毫秒,对吧?
  • new Date(1279340983000L) 是 2010-07-17。
  • java 中的时间戳使用毫秒,而不是秒

标签: java


【解决方案1】:

在您给定的时间没有包含时区,因此 Java 将采用本地时区,

    String createdTime = "1279340983";
    Date date1 = new Date(Long.parseLong(createdTime) * 1000); // right here
    System.out.println(date1.toString()); // this is what you are looking online
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss zzz"); // here you would have to customize the output format you are looking for
    System.out.println(sdf1.format(date1));

输出

Sat Jul 17 09:59:43 IST 2010 // this would be your online result 
2010-07-17 09:59:43 IST      // this is something you want to change ,

如果您愿意,您可能想要更改时区

sdf1.setTimeZone(TimeZone.getTimeZone("GMT"));

输出 格林威治标准时间 2010-07-17 04:29:43

【讨论】:

  • 这正是我要找的。这里要注意的是将 createdTime 从秒转换为毫秒
  • @SrinivasDJ,是的,你是对的
【解决方案2】:

您正在使用的在线转换器将日期转换为 。 Java 的Date 构造函数使用milliseconds,而不是秒。您需要将答案乘以 1000 才能匹配。

    String createdTime = "1279340983";
    Date date1 = new Date(Long.parseLong(createdTime) * 1000); // right here
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println(sdf1.format(date1));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    相关资源
    最近更新 更多