I need a date pattern to generate date string like this : 2019-12-18T17:11:24.2646051+03:30
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.?XXX").format(new Date())
What should I write instead of '?' ?
I need a date pattern to generate date string like this : 2019-12-18T17:11:24.2646051+03:30
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.?XXX").format(new Date())
What should I write instead of '?' ?
First point, get rid of SimpleDateFormat
. That class is notoriously troublesome and long outdated. Also there is no way that SimpleDateFormat
can produce 7 decimals on the seconds.
Second point, you probably don’t need to print 7 decimals on the seconds. Your format exemplified through 2019-12-18T17:11:24.2646051+03:30
is ISO 8601. In ISO 8601 the number of decimals on the seconds is free, so everyone should accept if you give them a string with 3 decimals, 9 decimals or no decimals at all (in the last case leave out the decimal point too).
So the easy solution is:
String desiredString
= OffsetDateTime.now(ZoneId.systemDefault()).toString();
System.out.println(desiredString);
Output when I ran the code just now:
2019-12-28T11:46:07.308+01:00
I am using java.time, the modern Java date and time API. And I am exploiting the fact that the toString
methods of the date and time classes of java.time print ISO 8601 format. So we need no explicit formatter so far.
If you do want or need 7 decimals, do use a DateTimeFormatter
:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral('T')
.appendPattern("HH:mm:ss.SSSSSSSXXX")
.toFormatter();
String desiredString = OffsetDateTime.now(ZoneId.systemDefault())
.format(formatter);
2019-12-28T11:48:52.3840000+01:00
It is possible to specify the formatter using a format pattern string only, but I prefer to reuse the built-in ISO_LOCAL_DATE
formatter for the date part also when the code gets a few lines longer.
You can use S
for the milliseconds. See this documentation page. You cannot use more than 3 though; there seems to be no support for microseconds or more fine-grained options.
import java.text.SimpleDateFormat;
import java.util.Date;
class Main {
public static void main(String[] args) {
String s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").format(new Date());
System.out.println(s);
}
}
Example output:
2019-12-28T10:28:02.933Z
If you do need more granularity, using the Instant.now()
function might be an option, although the following code will only produce 6 digits (microseconds, no nanoseconds):
import java.time.Instant;
class Main {
public static void main(String[] args) {
System.out.println(Instant.now().toString());
}
}
Example output:
2019-12-28T10:31:56.477551Z
See this answer for more info.