我正在从数据库中获取一个Date数据类型,就像这样Mon Sep 14 11:30:00 GMT+03:00 2020.I想要将这个值更改为一个字符串,所以我使用了这个函数。
public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm";
public static String dateToString(Date date){
DateFormat dateFormat = new SimpleDateFormat(General.DATE_FORMAT);
dateFormat.setTimeZone(TimeZone.getDefault());
if(date == null)
return "";
return dateFormat.format(date);
}这个函数给了我这个输出2020-09-14 11:30,但是根据我的安卓设备时区,它应该是2020-09-14 02:30。有什么建议吗?
发布于 2020-09-15 16:15:29
你可以使用来做这件事,现在可以通过Android API Desugaring降低Android API的级别。
public static void main(String[] args) {
// (nearly) your example pattern for output (u is better here)
final String DATE_FORMAT = "uuuu-MM-dd HH:mm";
// use it to create an output formatter
DateTimeFormatter outputDtf = DateTimeFormatter.ofPattern(DATE_FORMAT);
// your example String
String exampleDate = "Mon Sep 14 11:30:00 GMT+03:00 2020";
// parse it with a suitable formatter using a specific pattern and a Locale for names
DateTimeFormatter parserDtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss O uuuu",
Locale.ENGLISH);
// then parse the example String
OffsetDateTime odt = OffsetDateTime.parse(exampleDate, parserDtf);
// get your local offset (the one of your device)
ZoneOffset localOffset = OffsetDateTime.now().getOffset();
// and adjust the offset to your local one
OffsetDateTime localOdt = odt.withOffsetSameInstant(localOffset);
// and output it (on android, use log...)
System.out.println(odt.format(outputDtf)); // example datetime
System.out.println(localOdt.format(outputDtf)); // same time in local offset
}此代码输出
2020-09-14 11:30
2020-09-14 10:30请注意,输出--当然--是我当前的偏移量,也就是UTC+02:00。
发布于 2020-09-15 16:25:53
试用Locale的getDefault()方法
public static String dateToString(Date date){
DateFormat dateFormat = new SimpleDateFormat(General.DATE_FORMAT, Locale.getDefault());
dateFormat.setTimeZone(TimeZone.getDefault());
if(date == null)
return "";
return dateFormat.format(date);
}希望它能为你工作。谢谢。
发布于 2020-09-15 15:46:19
尝试在此之前设置
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));https://stackoverflow.com/questions/63897101
复制相似问题