获得ISO 8601格式的当前时刻UTC的最优雅的方式是什么?它看起来应该像:2010-10-12 t8: 50z。

例子:

String d = DateFormat.getDateTimeInstance(DateFormat.ISO_8601).format(date);

当前回答

我在Android中使用Calendar和SimpleDateFormat。下面的方法返回一个带有“GMT”时区的日历(这是通用时区)。然后,您可以使用Calendar类的setTimeZone()方法在不同的时区之间设置小时。

private static final String GMT = "GMT";
private static final String DATE_FORMAT_ISO = "yyyyMMdd'T'HHmmss";

public static Calendar isoToCalendar(final String inputDate) {
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(GMT));
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_ISO, Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone(GMT));
        Date date = dateFormat.parse(inputDate);
        calendar.setTime(date);
    } catch (ParseException e) {
        Log.e("TAG",e.getMessage());
    }
    return calendar;
}

记住: Date类不知道TimeZone的存在。因此,如果调试一个日期,总是会看到当前时区的日期。

其他回答

试试这个,

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ");
        String date=sdf.format (new Date() );

它的ISO 8601格式

从Java 8开始,你可以简单地做:

Instant.now().toString();

来自java.time.Instant文档:

现在 公共静态即时现在() 从系统时钟中获取当前时刻。 这将查询系统UTC时钟以获得当前时刻。

 

toString toString() 使用ISO-8601表示法的该瞬间的字符串表示法。 使用的格式与DateTimeFormatter.ISO_INSTANT相同。

这里优化了整个类,以便调用“now()”不做任何它必须做的事情。

public class Iso8601Util
{
    private static TimeZone tz = TimeZone.getTimeZone("UTC");
    private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");

    static
    {
        df.setTimeZone(tz);
    }

    public static String now()
    {
        return df.format(new Date());
    }
}
DateTimeFormatter.ISO_DATE_TIME
        .withZone(ZoneOffset.UTC)
        .format(yourDateObject.toInstant())
private static String getCurrentDateIso()
{
    // Returns the current date with the same format as Javascript's new Date().toJSON(), ISO 8601
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    return dateFormat.format(new Date());
}