问题
I am parsing the date as:
public class Consts{
public static final SimpleDateFormat DATE_FORMATTER_WITHOUT_TIME_ZONE = new SimpleDateFormat(
"yyyy-MM-dd HH:mm");
public static final SimpleDateFormat DATE_FORMATTER_2 = new SimpleDateFormat(
"MM-dd-yyyy HH:mm:ss ZZZZ");
}
cDate = new GregorianCalendar();
sDate = new GregorianCalendar();
eDate = new GregorianCalendar();
if (mStartTimeTV.getText().toString().equals("Now")) {
sDate.setTime(cDate.getTime());
} else {
sDate.setTime(Consts.DATE_FORMATTER_WITHOUT_TIME_ZONE
.parse(mStartTimeTV.getText().toString()));
}
if (!mEndTimeTV.getText().toString().equals("")) {
eDate.setTime(Consts.DATE_FORMATTER_WITHOUT_TIME_ZONE
.parse(mEndTimeTV.getText().toString()));
} else {
eDate.setTime(sDate.getTime());
// eDate = sDate;
}
And then i format the date as below before sending it to the server.:
request.addProperty("StartTime",
Consts.DATE_FORMATTER_2.format(sDate.getTime()));
request.addProperty("EndTime",
Consts.DATE_FORMATTER_2.format(eDate.getTime()));
But the thing is that on devices running 4.1.2 it is sending the date as:
Start Date: 03-23-2015 21:17:20 +0500
End Date : 10-23-2015 21:15:00 +0500
which throws exception on the server side.
But on the other devices it is sending dates as:
Start Date: 03-23-2015 21:12:13 GMT+05:00
End Date : 03-23-2015 21:16:00 GMT+05:00
which is required.
Am i doing something wrong? How can i prevent this problem so that all devices sends the same dates. (for example 03-23-2015 21:16:00 GMT+05:00
)
回答1:
The difference is caused by different locales set up on devices.
To mitigate the locale differences, you should use particular locale while formatting the date string. Here is a sample from my code, solving the same issue:
new SimpleDateFormat(C.FORMAT_DATETIMEZ, Locale.US).format(new Date(time))
回答2:
You can extend SimpleDateFormat and override its format(...) function as following:
public class ExSimpleDateFormat extends SimpleDateFormat{
private static final long serialVersionUID = -8275126788734707527L;
public ExSimpleDateFormat() {
super();
}
public ExSimpleDateFormat(String string, Locale us) {
super(string, us);
}
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, java.text.FieldPosition pos)
{
final StringBuffer buf = super.format(date, toAppendTo, pos);
buf.insert(buf.length() - 2, ':');
return buf;
};
}
And execute following code:
Calendar ca = Calendar.getInstance();
ca.setTimeInMillis(System.currentTimeMillis());
ExSimpleDateFormat exSimpleDateFormat = new ExSimpleDateFormat("dd-MM-yyyy HH:mm:ss 'GMT'Z", Locale.US);
exSimpleDateFormat.setTimeZone(ca.getTimeZone()); //your device timezone which can be GMT+xx:yy or GMT-xx:yy
String desiredTime = exSimpleDateFormat.format(ca.getTime());
Output would be like: 23-03-2015 23:12:52 GMT+05:00
Let me know if it helps. Thanks
来源:https://stackoverflow.com/questions/29215748/simpledateformat-parsing-date-differently-on-some-android-devices