在android中如何将字符串时间戳转换为date fromat?
说明: 我有一个字符串格式的时间戳,它来自json文件中的服务器。我的时间戳类似于这种格式的1454544000。我将这一次存储到字符串变量中 这是我的密码在android中如何将字符串时间戳转换为date fromat?,android,datetime,Android,Datetime,说明: 我有一个字符串格式的时间戳,它来自json文件中的服务器。我的时间戳类似于这种格式的1454544000。我将这一次存储到字符串变量中 这是我的密码 Timestamp ts=new Timestamp(System.currentTimeMillis()); Date d=new Date(ts.getTime()); Log.e("TimeStamp",""+d.toString()); 但它会返回当前的日期。我想转换我从json文件得到的时间戳 如何将上面的时间戳转换为date
Timestamp ts=new Timestamp(System.currentTimeMillis());
Date d=new Date(ts.getTime());
Log.e("TimeStamp",""+d.toString());
但它会返回当前的日期。我想转换我从json文件得到的时间戳
如何将上面的时间戳转换为date fromat???希望这有帮助
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));
将时间从json存储为long,而不是字符串,并将其传递到以下代码中:
String time = DateUtils.formatDateTime(this, 1454544000, DateUtils.FORMAT_SHOW_TIME));
String date = DateUtils.formatDateTime(this, 1454544000, DateUtils.FORMAT_SHOW_DATE));
将时间戳存储在名为timeinmillisecond的长类型变量中,然后
String dateString = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date(TimeinMilliSeccond));
代码应该如下所示:
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
的更多信息,您可以查看这个:试试这个
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);
请给出具有预期输出值的输入值的具体示例。“日期格式”太模糊。它返回相同的1970年1月18日。上面返回的答案不正确,因为DateUtils在秒(UNIX)上工作,但传递的值是ms,将该值乘以1000,您将得到正确的日期。它返回Sun Jan 18 05:24:50 GMT+05:30 1970,就像这样为什么它返回1970年