我有什么
我的服务器日期为w3c date format
2016-02-13T09:53:49.871Z ,用于通知
我想要什么
我想将w3c format
转换为device time zone
,然后从设备获取当前日期,以检查sever date
是否等于设备日期
我的问题
我在Parse error: 2016-03-10 15:45:36
Date formattedServerDeviceDate=new Date(serverDateDeviceFormat);
我的代码
public boolean isTodaysNotification(String serverDate)throws Exception{
boolean isTodaysNotification=false;
SimpleDateFormat simpleDateFormatW3C = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
simpleDateFormatW3C.setTimeZone(TimeZone.getTimeZone("GMT"));
Date dateServer = simpleDateFormatW3C.parse(serverDate);
TimeZone deviceTimeZone = TimeZone.getDefault();
SimpleDateFormat simpleDeviceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDeviceFormat.setTimeZone(deviceTimeZone);
String serverDateDeviceFormat = simpleDeviceFormat.format(dateServer);
Date formattedServerDeviceDate=new Date(serverDateDeviceFormat); // formatted to device time zone (w3c to utc)
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd"); // formatting to consider only "yyyy-MM-dd"
String strServerDate=simpleFormat.format(formattedServerDeviceDate); // server date
String strTodaysDate=simpleFormat.format(new Date()); // current date
if (new Date(strTodaysDate).compareTo(new Date(strServerDate))==0){
isTodaysNotification=true;
}
else {
isTodaysNotification=false;
}
return isTodaysNotification;
}
答案 0 :(得分:4)
java.util.Date
的基于字符串的构造函数需要一个由方法toString()
生成的格式的字符串。类似于"星期六,1995年8月12日13:30:00 GMT + 0430"。
另请参阅相关parser的说明。建议:不要使用弃用的东西。
最重要的是:您无法获得java.util.Date
的格式化实例。 此对象不带任何格式信息,但它只是一个长值的包装器。所以你试着"格式"日期对象是错误的。继续使用dateServer
。它在全球范围内具有相同的价值。
如何提供帮助?
您当然可以将Date
- 对象转换为Calendar
- 对象,并询问年,月,日。例如:
GregorianCalendar gcal = new GregorianCalendar(TimeZone.getDefault());
java.util.Date serverDate = new Date(); // here for demonstration, use that from server
gcal.setTime(serverDate);
int year = gcal.get(Calendar.YEAR);
int month = gcal.get(Calendar.MONTH) + 1;
int dayOfMonth = gcal.get(Calendar.DAY_OF_MONTH);
但是这里的一般问题开始了:为了进行仅日期比较,你需要知道服务器的时区应用相同的程序并比较日期组件(年,月,日) 。即使你知道服务器的时区,这有意义吗?客户为什么要关心服务器内部?
答案 1 :(得分:0)
尝试这种方法:使用simpleDeviceFormat.parse(...)代替new Date(String)
从字符串到日期
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date formattedServerDeviceDate = format.parse(serverDateDeviceFormat);
System.out.println(formattedServerDeviceDate);
} catch (ParseException e) {
e.printStackTrace();
}
答案 2 :(得分:0)
假设您需要检查在UTC时区表示为String
的日期时间是否属于默认时区的当前日期:
public boolean isToday(String utcDatetime, String format) throws Exception {
DateFormat sdf = new SimpleDateFormat(format);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar c1 = Calendar.getInstance(); // calendar with default TZ
Calendar c2 = Calendar.getInstance();
c1.setTime(sdf.parse(utcDatetime); // input datetime
c2.setTime(new Date()); // current datetime
return c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)
&& c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR);
}