[英]Calendar.getTime() to Date object
我有一個設置了UTC時區的Calendar實例,我必須是UTC,因為我必須與UTC服務器同步。
我需要從此Calendar創建一個Date對象,並使用Calendar.getTime()。
但是,當我嘗試打印出Date對象時,會看到另一個TimeZone(CEST而不是UTC)
TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar cal = Calendar.getInstance(timeZone);
cal.setTime(timeMillisecond);
Date d = cal.getTime();
Log.d("TAG", d.toString());
編輯:
當我將日期對象傳遞給服務器時,我使用的是CEST時區而不是UTC時區。
您可以使用sdf,設置其時區並進行相應的解析。
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
try {
Date dt = sdf.parse(sdf.format(Calendar.getInstance()));
} catch (ParseException e) {
e.printStackTrace();
}
這對我有用。
嘗試以下代碼,它將為您提供UTC日期。
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy dd,MM hh:mm:ss", Locale.getDefault());
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcTime = dateFormat.format(new Date(timeMillisecond));
Log.d("TAG", utcTime);
它將以yyyy dd,MM hh:mm:ss格式提供日期,但您可以根據需要提供其他格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.