问题
How can I convert current time to this format:
"2017-04-25T17:12:42+01:00"
The closest I could get is this:
"2017-05-16T19:58:21+0100"
by using this format:
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZ").format(new Date())
Thanks
回答1:
You should use the modern Java 8 java.time package, more specifically DateTimeFormatter, the ISO_OFFSET_DATE_TIME.
From the docs:
public static final DateTimeFormatter ISO_OFFSET_DATE_TIME
The ISO date-time formatter that formats or parses a date-time with an offset, such as '2011-12-03T10:15:30+01:00'.
Working code:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main
{
public static void main(String[] args)
{
ZonedDateTime date = ZonedDateTime.now();
String text = date.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
System.out.println(text);
}
}
Result:
> run Main
2017-05-19T13:03:16.167+02:00
回答2:
ZZZ
is RFC 822 time zone like this: -0800;
XXX
is ISO 8601 time zone like this: -08:00;
Use XXX
if want to second foramt and don't want use ISO_OFFSET_DATE_TIME
, for example, want to display “01/15/2000T14:44:59-08:00”:
DateTimeFormatter.ofPattern("MM/dd/yyyy'T'HH:mm:ssXXX").format(...);
回答3:
You can use "yyyy-MM-dd'T'HH:mm:ssXXX" as pattern instead of yyyy-MM-dd'T'HH:mm:ssZZZ, see the examples here
回答4:
SimpleDateFormat will do a thing for you
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
formatter.format(date);
来源:https://stackoverflow.com/questions/44067846/converting-current-time-to-this-format-2017-04-25t1712420100