【问题标题】:How to extract time from unix timestamp in java? [duplicate]如何从java中的unix时间戳中提取时间? [复制]
【发布时间】:2014-11-07 15:33:57
【问题描述】:

我是 java 新手,我正在制作一个天气应用程序。

我从 openweathermap 服务器获取 JSON 格式的数据。下面是格式

 "sys":{  
      "type":1,
      "id":7758,
      "message":0.2194,
      "country":"India",
      "sunrise":1410569741,
      "sunset":1410614119
   },

我想从中提取日出和日落,但我想要的只是时间而不是日期。 下面是我的代码

DateFormat df = DateFormat.getDateTimeInstance();

            String sunrise= df.format(new Date(json.getJSONObject("sys").getLong("sunrise")*1000).getTime());
            String sunset = df.format(new Date(json.getJSONObject("sys").getLong("sunset")*1000).getTime());

我的代码的问题是它给了我时间和日期,输出是 “2014 年 9 月 13 日上午 6:25:41”用于日出。日落也是如此。 ?

我该如何提取“6:25:41 AM”呢?我只想要时间而不是年/月/日

【问题讨论】:

  • 发帖前请搜索 StackOverflow。

标签: java date unix-timestamp


【解决方案1】:

试试这个方法

SimpleDateFormat df = new SimpleDateFormat("hh:mm:ss a",Locale.ENGLISH);
System.out.println(df.format(new Date()));

或者这样

DateFormat ddf = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.ENGLISH);
System.out.println(ddf.format(new Date()));

指定区域设置以确保您的安全并注意字母的大小写,例如 H 表示 24 小时制的一天中的小时,h 表示 12 小时制的一天中的小时。 refer

【讨论】:

  • 谢谢您,先生,您的回答完美。
  • 抱歉这么晚才问,格式为“hh:mm:ss a”,这个“a”代表什么??
  • 它代表上午/下午标记参考我给你的链接。
  • 非常感谢先生,解决了我所有的疑惑。
【解决方案2】:

您可以使用正确的格式来做到这一点:DateFormat.getTimeInstance()。

【讨论】:

  • 谢谢先生,我用simpledateformat找到了答案
猜你喜欢
  • 2019-06-10
  • 2020-12-16
  • 2013-07-02
  • 2013-08-02
  • 2012-11-11
  • 2013-03-20
  • 2015-01-10
  • 2016-08-10
  • 1970-01-01
相关资源
最近更新 更多