将12小时时间格式转换为utc后得到错误的结果。
String inputPa = "hh:mm a";
String OutPa = "yyyy-MM-dd'T'HH:mm:ss'Z'";
SimpleDateFormat inputPatter = new SimpleDateFormat(inputPa);
SimpleDateFormat outputPatter = new SimpleDateFormat(OutPa);
Date date1 = null;
String str1 = null;
try {
date1 = inputPatter.parse(txtStartTime.getText().toString());
str1 = outputPatter.format(date1);
Log.d("mycheck", str1);
} catch (ParseException e) {
e.printStackTrace();
}
我想您想在您的时区显示今天的日期。
String inputPa = "hh:mm a";
DateTimeFormatter timeFormatter12Hours = DateTimeFormatter.ofPattern(inputPa, Locale.ENGLISH);
ZoneId zone = ZoneId.of("America/Detroit");
String timeString = "11:34 AM";
LocalTime time = LocalTime.parse(timeString, timeFormatter12Hours);
Instant inst = LocalDate.now(zone).atTime(time).atZone(zone).toInstant();
System.out.println(inst);
此示例的输出是:
2020-05-30T15:34:00Z
我不会费心将Instant
明确转换为字符串。当您打印时,它以所需的格式以UTC进行打印,因此隐式调用了其toString
方法(格式为ISO 8601,国际标准)。
请填写您所需的时区。要依赖设备的时区设置,请将zone
设置为ZoneId.systemDefault()
。
我当然很高兴使用现代的Java日期和时间API java.time。您也可以在Android版本上执行此操作,请参见下面的详细信息。
java.time在较新和较旧的Android设备上均可正常运行。它只需要至少Java 6。
org.threeten.bp
导入日期和时间类。java.time
。java.time
的向后移植到Java 6和7(JSR-310的ThreeTen)。请尝试此代码。它为我工作:
Date myDate = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTime(myDate);
Date time = calendar.getTime();
SimpleDateFormat outputFmt = new SimpleDateFormat("MMM dd, yyy h:mm a zz");
String dateAsString = outputFmt.format(time);
System.out.println(dateAsString);
public tring getCurrentUTC(Date time) {
SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
outputFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
return outputFmt.format(time);
}
您可以使用此代码获取当前UTC时间。
对于您的问题,您只需要将时间字符串转换为Date
格式。