i have the following date 2017-02-19T12:23:37.000000-00:00
And this code :
Long tt = null;
String date = "2017-02-19T12:23:37.000000-00:00";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
try {
Date parsedDate = formatter.parse(date);
tt = parsedDate.getTime();
} catch (ParseException e) {
System.out.println(e);
tt = (long) 9999999;
}
System.out.println(tt);
Output :
java.text.ParseException: Unparseable date: "2017-02-19T12:23:37.000000-00:00"
9999999
Thank you for the help.
Your millisecond part has 6 digits not three, and the timezone is given not as an RFC 822 time zone but as an ISO 8601 time zone.
This will work:
"yyyy-MM-dd'T'HH:mm:ss.SSSSSSX"
As was correctly pointed out in the comments, this will garble up the millisecond part if it ever deviates from 000000.
Since Java 8 there is a much better way to parse dates and times. For ISO-8601 dates as yours, simply use this:
OffsetDateTime.parse("2017-02-19T12:23:37.000000-00:00")
Also see Basil Bourque's great answer for a more detailed explanation.
tl;dr
OffsetDateTime.parse( "2017-02-19T12:23:37.000000-00:00" )
Use java.time
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Milliseconds vs nanoseconds
The legacy classes support only milliseconds resolution, limited to three decimal places of fractional second. The java.time classes use nanoseconds resolution, for up to nine decimal places of fractional second. Your example data of six decimal places is for microseconds.
ISO 8601
Your input string happens to be in standard ISO 8601 format.
Well, almost standard: Your example has a negative zero offset-from-UTC. A negative zero offset is explicitly forbidden by the ISO 8601 standard. The standard requires a zero offset be marked with as a positive number with the + sign rather than - sign. However, RFC 3339 which claims to be a profile of ISO 8601 violates this rule with the unfortunate and unwise choice as a different connotation.
The java.time classes use ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern at all.
OffsetDateTime
Fortunately for you, the OffsetDateTime class tolerates the negative zero offset when parsing your input.
String input = "2017-02-19T12:23:37.123456-00:00" ;
OffsetDateTime odt = OffsetDateTime.parse( input );
See this code run live at IdeOne.com.
odt.toString(): 2017-02-19T12:23:37.123456Z
Notice the use of ISO 8601 formatting by OffsetDateTime::toString when generating a string from our OffsetDateTime. The Z on the end is short for Zulu, and means UTC.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Your input date doesn't match the pattern you specified. Try changing the pattern:
String date = "2017-02-19T12:23:37.000000-00:00";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX");
For more information, you can look at documentation examples here.
Related
How do I convert a string of ISO-8601 datetime (ex: 2012-05-31T13:48:04Z) to number of seconds( 10 digit integer) using Java?
try this way
String DateStr="2012-05-31T13:48:04Z";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date d=sdf.parse(DateStr);
System.out.println(d.getTime());
output 1338452284000
From the comments of OP
getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.Source
using SimpleDateFormat and use format like yyyy-MM-dd 'T' HH:mm:ss 'Z'
tl;dr
Instant.parse( "2012-05-31T13:48:04Z" )
.getEpochSecond()
1338472084
See this code run live at IdeOne.com.
Using java.time
Much easier with the java.time classes that supplant the troublesome old legacy date-time classes.
Easy to parse your input string as the java.time classes use ISO 8601 formats by default when generating/parsing strings. So no need to specify a formatting pattern.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.parse( "2012-05-31T13:48:04Z" ) ;
I am guessing that by “seconds” you meant the number of seconds elapsed since the beginning of 1970 UTC (1970-01-01T00:00:00Z). The Instant class can tell you the number of seconds since that Unix epoch.
long secondsSinceEpoch = instant.getEpochSecond() ;
1338472084
Beware of data loss, obviously. You are ignoring any fractional second that may be present in your date-time value.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
So, basically I am trying to achieve the following format in a String:
2012-06-17T08:00:00.000+01:00
I get the original date in a string format which I then parse into different formats.
When I use SimpleDateFormat with the format as (yyyy-MM-dd'T'HH:mm:ss.sssZ), I get the following output:
2013-06-17T07:00:00.000+0530
Here +0530 should be +05:30
When I set the above date into a Calendar type and then convert it to a string I get the following format:
2013-06-17T07:00:00+05:30
Here I don't get the .000 after the seconds.
Any ideas how this can be achieved, without using JodaTime. Need manipulations in Date, String and Calendar type only
Firstly to get the extra : use XXX in your formatter like so and use Uppercase S to get the milliseconds
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
UPDATE: Above doesn't work on 1.6
Yo could try the following however
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
{
public StringBuffer format(Date date, StringBuffer toAppendTo, java.text.FieldPosition pos)
{
StringBuffer toFix = super.format(date, toAppendTo, pos);
return toFix.insert(toFix.length()-2, ':');
};
See this post for more
SimpleDateFormat pattern
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
tl;dr
OffsetDateTime.parse( "2012-06-17T08:00:00.000+01:00" ) // Parse string in standard ISO 8601 format to an object.
.format( // Generate a String representing the value of that `OffsetDateTime` object.
DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSXXXXX" ) // Specify a formatting pattern to force the seconds and fractional second even if zero.
) // Return a `String` object.
2012-06-17T08:00:00.000+01:00
java.time
The modern approach uses the java.time classes rather than the troublesome old legacy date-time classes. Avoid Date, Calendar, and SimpleDateFormat.
ISO 8601
Your desired format happens to be standard ISO 8601 format. The java.time classes use the standard format by default when parsing/generating strings. So no need to specify a formatting pattern.
OffsetDateTime
Your input string includes an offset-from-offset but not a time zone. So we parse as a OffsetDateTime object.
OffsetDateTime odt = OffsetDateTime.parse( "2012-06-17T08:00:00.000+01:00" ) ;
To generate a string in the same standard ISO 8601 format, simply call toString. By default, the least significant parts are omitted if zero. So no seconds or fractional second appear using your example data.
String output = odt.toString() ;
2012-06-17T08:00+01:00
If you want to force the seconds and fractional second even when zero, specify a formatting pattern.
OffsetDateTime odt = OffsetDateTime.parse( "2012-06-17T08:00:00.000+01:00" );
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSXXXXX" );
String output = odt.format( f );
2012-06-17T08:00:00.000+01:00
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I received from a SOAP message the follow date:
2012-11-16T02:02:05Z
How to parse to Date? What means this T and the Z in the date according with the SOAP specification?
I can parse correctly doing this way:
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(paymentDate);
Thanks #vikdor!
tl;dr
Instant.parse( "2012-11-16T02:02:05Z" )
ISO 8601
Your input string is in standard ISO 8601 format. That standard defines many useful, practical, unambiguous textual formats for representing date-time values.
The ISO 8601 formats are commonly adopted by modern protocols, such as XML schema, SOAP, etc., supplanting the clumsy outmoded formats such as RFC 1123 / RFC 822.
Your particular format from ISO 8601 uses:
T to separate the year-month-day portion from the hour-minute-second portion.
Z, short for Zulu, to indicate UTC time (an offset-from-UTC of +00:00).
Using java.time
Use the modern classes in the java.time package. They use ISO 8601 formats by default when parsing/generating strings.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.parse( "2012-11-16T02:02:05Z" ) ;
Capture the current moment in UTC.
Instant instant = Instant.now() ;
Generate a string in standard format by simply calling toString.
String output = instant.toString() ;
2017-07-26T01:23:45.704781401Z
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I need to convert a timestamp string to java.util.Date. E.g.:
MMDDYYHHMMSS to MM-DD-YY HH-MM-SS
Where MM is month, DD is date, YY is year, HH is hours, MM is minutes and SS is seconds.
You can do it like this:
DateFormat format = new SimpleDateFormat("MMddyyHHmmss");
Date date = format.parse("022310141505");
but I would strongly recommend that you use Joda Time instead. It's a better date/time library by a long, long way. In particular, the formatters/parsers in Joda Time are thread-safe, so you can reuse them freely and statically; java.text.SimpleDateFormat isn't thread-safe, so you either need to create one per thread or serialize access to it with a synchronized block.
tl;dr
java.time.LocalDateTime.parse(
"012318123456" ,
DateTimeFormatter.ofPattern( "MMdduuHHmmss" )
).format(
DateTimeFormatter.ofPattern( "MM-dd-uu HH-mm-ss" )
)
01-23-18 12-34-56
java.time
The modern approach uses the java.time classes.
Define a formatting pattern to match your input string.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMdduuHHmmss" ) ;
Your two-digit year will be interpreted as being 21st century ( 20xx ).
Parse as a LocalDateTime because your input string lacks any indicator of time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( "012318123456" , f ) ;
ldt.toString(): 2018-01-23T12:34:56
Generate a string in your desired format.
DateTimeFormatter fOut = DateTimeFormatter.ofPattern( "MM-dd-uu HH-mm-ss" ) ;
String output = ldt.format( fOut );
01-23-18 12-34-56
ISO 8601
Both of your formats are terrible, for multiple reasons.
When serializing date-time values, use the standard ISO 8601 formats whenever possible. They are designed to be practical, easy to parse by machine, easy to read by humans across cultures.
For a date-time time such as yours, the T in the middle separates the date portion from the time-of-day portion.
2018-01-23T12:34:56
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
use a SimpleDateFormat with an appropriate format string (be careful to use the correct format letters, uppercase and lowercase have different meanings!).
I have to use a custom date format in Java. It contains microseconds although Java doesn't provide support for microseconds. Because of that I filled the time pattern with zeroes, which work fine when formatting, but I cannot parse date-strings with that pattern.
Is there a simple workaround or must I handle microseconds on my own (with String functions)?
#Test
public void testDateFormat() throws ParseException {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS000");
String theDate = format.format(new Date());
// this will fail:
format.parse(theDate);
}
java.text.ParseException: Unparseable date: "2010-01-25-12.40.35.769000"
Your problem is that the pattern used in SimpleDateFormat unfortunately have different meanings depending on whether it is used as a parser or as a formatter. As a formatter, your pattern does what is expected, the output will end with the millisecond value formatted as three digits followed by three 0 characters, e.g:
2010-01-25-14.17.47.307000
Used as a parser, the "SSS" pattern will however match an arbitrary number of digits and parse the above example as 307000 ms. After having parsed the ms field, the parser will still look for a "000" substring and fail with an exception, since you've reached the end of the input string, without fulfilling the requirements of the pattern.
Since there is no pattern for a µs value in SimpleDateFormat, you will have to write your own wrapper to strip the input string for the last three 0 characters, before feeding it to SimpleDateFormat.
In addition to jarnbjo's answer, if you need the microseconds, you might be able to use java.sql.Timestamp:
Date dateToMillis = format.parse(theDate.substring(0, 23));
DateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Timestamp timestamp = Timestamp.valueOf(timestampFormat.format(dateToMillis) + theDate.substring(23,26));
tl;dr
LocalDateTime.parse(
"2010-01-25-12.40.35.769000" ,
DateTimeFormatter.ofPattern( "uuuu-MM-dd-HH.mm.ss.SSSSSS" )
)
Using java.time
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
These old classes were limited to tracking milliseconds, three digits of decimal fraction. The modern java.time classes resolve to nanoseconds, for nine digits of decimal fraction.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd-HH.mm.ss.SSSSSS" ) ;
LocalDateTime ldt = LocalDateTime.parse( "2010-01-25-12.40.35.769000" );
ldt.toString(): 2010-01-25T12:40:35.769
ISO 8601
Tip: Rather than invent your own format to textually represent a date-time value, stick to the standard ISO 8601 formats.
The java.time classes use the standard formats by default. You can see that format in the output above. The T separates the date portion from the time-of-day portion.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Add a '' around the zeros, like so: "yyyy-MM-dd-HH.mm.ss.SSS'000'"
Date and time formats are specified by
date and time pattern strings. Within
date and time pattern strings,
unquoted letters from 'A' to 'Z' and
from 'a' to 'z' are interpreted as
pattern letters representing the
components of a date or time string.
Text can be quoted using single quotes
(') to avoid interpretation. "''"
represents a single quote. All other
characters are not interpreted;
they're simply copied into the output
string during formatting or matched
against the input string during
parsing.