【问题标题】:How can i convert string timestamp into date fromat in android?如何在android中将字符串时间戳转换为日期格式?
【发布时间】:2016-04-02 05:58:12
【问题描述】:

说明: 我有一个字符串格式的时间戳,它来自 json 文件中的服务器。我的时间戳就像 1454544000 这种格式。我把这个时间存入 String 变量中。

这是我的代码

Timestamp ts=new Timestamp(System.currentTimeMillis());
Date d=new Date(ts.getTime());
Log.e("TimeStamp",""+d.toString());

但它返回当前的今天日​​期。我想转换我从 json 文件中获得的时间戳。

如何将上述时间戳转换为日期 fromat????

【问题讨论】:

  • 请给出一个输入值与预期输出值的具体例子。 “日期格式”太模糊了。

标签: android datetime


【解决方案1】:

代码应如下所示:

long timestamp = 1454544000;
Date date = new Date(timestamp);

如果您还想自定义日期格式,可以尝试使用SimpleDateFormat。这里还有一个示例代码:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String formattedDate = formatter.format(date);

有关SimpleDateFormat的更多信息,您可以查看这个:Simple Date Format

【讨论】:

  • 它返回 Sun Jan 18 05:24:50 GMT+05:30 1970 那样
  • 为什么是 1970 年的回归年
【解决方案2】:

将时间从 json 中存储为 long 而不是字符串,并将其传递到下面的代码中:

String time = DateUtils.formatDateTime(this, 1454544000, DateUtils.FORMAT_SHOW_TIME));
String date =  DateUtils.formatDateTime(this, 1454544000, DateUtils.FORMAT_SHOW_DATE));

【讨论】:

  • 它返回相同的 1970 年 1 月 18 日
  • 以上返回不正确的答案,因为 DateUtils 在秒 (UNIX) 上工作,但传递的值为 ms,将值乘以 1000,您将得到正确的日期。
【解决方案3】:

希望对你有帮助

import java.util.Date;
public class HelloWorld{

     public static void main(String []args){
        //Since you mentioned that you have timestamp in string format, so I have taken timestamp as string and parsed it to long in Date()
        String timestamp = "1454544000" ; //Example -> in ms
        Date d = new Date(Long.parseLong(timestamp));
        System.out.println(d);
    }
}

所以你可以在你的 Android 应用中使用这两行代码:

String timestamp = "1454544000" ; //Example -> in ms
Date d = new Date(Long.parseLong(timestamp));

【讨论】:

    【解决方案4】:

    将您的时间戳存储在名为 TimeinMilliSeccond 的长类型变量中,然后

    String dateString = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date(TimeinMilliSeccond));
    

    【讨论】:

      【解决方案5】:

      试试这个

       Use below method for Convert JsonDate to normal format.
      
      
      public static String ConvertJsonDate(String jsondate) {
      
          jsondate = jsondate.replace("/Date(", "").replace(")/", "");
          long time = Long.parseLong(jsondate);
          Date d = new Date(time);
          return new SimpleDateFormat("dd/MMM/yyyy").format(d).toString();
         }
      
          //Now you use this method this way
          String date1 = ConvertJsonDate("Yourjsondate"); //give argument like 1454544000 
          System.out.println(date1);
      

      【讨论】:

        猜你喜欢
        • 2011-10-23
        • 1970-01-01
        • 2017-12-30
        • 2011-05-21
        • 2020-09-23
        • 1970-01-01
        • 2012-04-19
        • 1970-01-01
        相关资源
        最近更新 更多