简体   繁体   English

Calendar.getTime()到Date对象

[英]Calendar.getTime() to Date object

I've an instance of a Calendar setted with UTC time zone, I need to be UTC becouse I've to sync with a server that is UTC. 我有一个设置了UTC时区的Calendar实例,我必须是UTC,因为我必须与UTC服务器同步。

I need to create a Date object from this Calendar, and I use Calendar.getTime(). 我需要从此Calendar创建一个Date对象,并使用Calendar.getTime()。

But when I try to print out the Date object I see it with a different TimeZone (CEST instead of UTC) 但是,当我尝试打印出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());

EDIT: 编辑:

When I pass the date object to the server, I get it with CEST timezone instead of UTC time zone. 当我将日期对象传递给服务器时,我使用的是CEST时区而不是UTC时区。

You can use sdf, set its timezone and parse it accordingly. 您可以使用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();
                        }

This worked for me. 这对我有用。

Try the below code, it will provide you the date in UTC. 尝试以下代码,它将为您提供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);

It will provide you the date in yyyy dd,MM hh:mm:ss format but you can provide other format according to your need. 它将以yyyy dd,MM hh:mm:ss格式提供日期,但您可以根据需要提供其他格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM