我正在尝试将在Android设备上的区域设置时创建的日期时间格式转换为GMT。我无法获得正确的值。而且生成的dateTime是针对android的本地时间。如何将其转换为精确的GMT unixtime?
String dateTime="02-02-2016 8:28 PM";
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = null;
try {
date = format.parse(dateTime);
System.out.println("Date ->" + date);
} catch (Exception e) {
e.printStackTrace();
}
long unixtime = date.getTime() / 1000;
答案 0 :(得分:1)
try{
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sourceFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Log.v("Current time", ""+ sourceFormat.format(new Date()));
Date parsed = sourceFormat.parse(sourceFormat.format(new Date())); // => Date is in UTC now
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
SimpleDateFormat destFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
destFormat.setTimeZone(tz);
// String result = destFormat.format(parsed);
String result = destFormat.format(sourceFormat.parse(sourceFormat.format(new Date())));
Log.e("result", ""+result);
// 2015-11-26 02:07:59
SimpleDateFormat UTCFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat severFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat localFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
UTCFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
TimeZone tz1 = TimeZone.getTimeZone("America/Los_Angeles");
severFormat.setTimeZone(tz1);
localFormat.setTimeZone(TimeZone.getDefault());
Date serverDate = severFormat.parse(result);
Date utcDate = UTCFormat.parse(UTCFormat.format(serverDate));
String localDate = localFormat.format(utcDate);
Log.e("localDate", ""+localDate);
}catch(ParseException e){
e.printStackTrace();
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}