我正在尝试将UTC时间转换为当地时间。
UTC时间:1465389050
我尝试了下面的代码。但它没有打印或显示结果。所以我不确定这段代码是否有效。
MainActivity.java:
String created = "1465389050";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date myDate = simpleDateFormat.parse(created);
Log.e("myDate", ""+myDate);
Toast.makeText(getApplicationContext(), myDate.toString(), Toast.LENGTH_LONG).show();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
答案 0 :(得分:0)
试试这个
long timestamp = 1465389050L;
Date date = new Date(timestamp);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID()));
calendar.setTime(date);
现在您可以将UTC时间转换为当地时间
答案 1 :(得分:0)
正如我在评论中所说:new Date(YourTimestampAsLong * 1000)
已经给你当地时间了。无需设置TimeZone。
Date date = new Date((long)1465389050 * 1000);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
输出:
2016-06-08 14:30:50