UTC 中的 SimpleDateFormat 到给定格式的字符串
SimpleDateFormat in UTC to String in given format
我需要在此行中添加一些内容:
String date = new SimpleDateFormat("dd-MMM-yy hh.mm.ss").format(new Date()).toUpperCase();
因为我需要来自 UTC 的时间,而不是来自我当前位置的时间。你能帮帮我吗?
您可以使用这个:
final SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy hh.mm.ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());
或查看 java8 LocalDateTime 和 DateTimeFormat API。 java.util.Date 尤其是 SimpleDateFormat 有点过时了,我建议尽可能不要使用 SimpleDateFormat,因为它不是线程保存,在使用流或其他东西时可能会咬你。
Java 8个选择:
String now = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("dd-MMM-yy HH.mm.ss"));
我需要在此行中添加一些内容:
String date = new SimpleDateFormat("dd-MMM-yy hh.mm.ss").format(new Date()).toUpperCase();
因为我需要来自 UTC 的时间,而不是来自我当前位置的时间。你能帮帮我吗?
您可以使用这个:
final SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy hh.mm.ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());
或查看 java8 LocalDateTime 和 DateTimeFormat API。 java.util.Date 尤其是 SimpleDateFormat 有点过时了,我建议尽可能不要使用 SimpleDateFormat,因为它不是线程保存,在使用流或其他东西时可能会咬你。
Java 8个选择:
String now = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("dd-MMM-yy HH.mm.ss"));