Custom date format cannot be parsed. (Java) - java

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.

Related

Cannot parse String in ISO 8601 format, lacking colon in offset, to Java 8 Date

I'm a little bit frustrated of java 8 date format/parse functionality. I was trying to find Jackson configuration and DateTimeFormatter to parse "2018-02-13T10:20:12.120+0000" string to any Java 8 date, and didn't find it.
This is java.util.Date example which works fine:
Date date = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZZZ")
.parse("2018-02-13T10:20:12.120+0000");
The same format doesn't work with new date time api
ZonedDateTime dateTime = ZonedDateTime.parse("2018-02-13T10:20:12.120+0000",
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'hh:mm:ss.SSSZZZ"));
We should be able to format/parse date in any format suitable for FE UI application. Maybe I misunderstand or mistake something, but I think java.util.Date gives more format flexibility and easier to use.
tl;dr
Until bug is fixed:
OffsetDateTime.parse(
"2018-02-13T10:20:12.120+0000" ,
DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSX" )
)
When bug is fixed:
OffsetDateTime.parse( "2018-02-13T10:20:12.120+0000" )
Details
You are using the wrong classes.
Avoid the troublesome old legacy classes such as Date, Calendar, and SimpleDateFormat. Now supplanted by the java.time classes.
The ZonedDateTime class you used is good, it is part of java.time. But it is intended for a full time zone. Your input string has merely an offset-from-UTC. A full time zone, in contrast, is a collection of offsets in effect for a region at different points in time, past, present, and future. For example, with Daylight Saving Time (DST) in most of North America, the offsets change twice a year growing smaller in the Spring as we shift clocks forward an hour, and restoring to a longer value in the Autumn when we shift clocks back an hour.
OffsetDateTime
For only an offset rather than a time zone, use the OffsetDateTime class.
Your input string complies with the ISO 8601 standard. The java.time classes use the standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
OffsetDateTime odt = OffsetDateTime.parse( "2018-02-13T10:20:12.120+0000" );
Well, that should have worked. Unfortunately, there is a bug in Java 8 (at least up through Java 8 Update 121) where that class fails to parse an offset omitting the colon between hours and minutes. So the bug bites on +0000 but not +00:00. So until a fix arrives, you have a choice of two workarounds: (a) a hack, manipulating the input string, or (b) define an explicit formatting pattern.
The hack: Manipulate the input string to insert the colon.
String input = "2018-02-13T10:20:12.120+0000".replace( "+0000" , "+00:00" );
OffsetDateTime odt = OffsetDateTime.parse( input );
DateTimeFormatter
The more robust workaround is to define and pass a formatting pattern in a DateTimeFormatter object.
String input = "2018-02-13T10:20:12.120+0000" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSX" );
OffsetDateTime odt = OffsetDateTime.parse( input , f );
odt.toString(): 2018-02-13T10:20:12.120Z
By the way, here is a tip: I have found that with many protocols and libraries, your life is easier if your offsets always have the colon, always have both hours and minutes (even if minutes are zero), and always use a padding zero (-05:00 rather than -5).
DateTimeFormatterBuilder
For a more flexible formatter, created via DateTimeFormatterBuilder, see this excellent Answer on a duplicate Question.
Instant
If you want to work with values that are always in UTC (and you should), extract an Instant object.
Instant instant = odt.toInstant();
ZonedDateTime
If you want to view that moment through the lens of some region’s wall-clock time, apply a time zone.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = odt.atZoneSameInstant( z );
See this code run live at IdeOne.com.
All of this has been covered many times in many Answers for many Questions. Please search Stack Overflow thoroughly before posting. You would have discovered many dozens, if not hundreds, of examples.
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, Java SE 10, 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.
Short: Not a bug, just your pattern is wrong.
Please use the type OffsetDateTime which is especially designed for time zone offsets and use a pattern this way:
OffsetDateTime odt =
OffsetDateTime.parse(
"2018-02-13T10:20:12.120+0000" ,
DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSZZZ" )
)
Problems in detail:
a) 12-hour-clock versus 24-hour-clock
"h" indicates the hour of AM/PM on a 12-hour-clock but you obviously need "H" for the 24-hour-clock as required by ISO-8601.
b) The form of zero offset
If you want to parse zero offset like "+0000" instead of "Z" (as described in ISO-paper) you should not use the pattern symbol "X" but "ZZZ". Citing the pattern syntax:
Offset Z: This formats the offset based on the number of pattern
letters. One, two or three letters outputs the hour and minute,
without a colon, such as '+0130'. The output will be '+0000' when the
offset is zero.
c) Your input is NOT ISO-8601-compatible therefore no bug in Java
Your assumption that "2018-02-13T10:20:12.120+0000" shall be valid ISO is wrong because you are mixing basic format (in the offset part) and extended format which is explicitly prohibited in ISO-paper (see sections 4.3.2 (example part) and 4.3.3d). Citing ISO-8601:
[...]the expression shall either be completely in basic format, in which
case the minimum number of separators necessary for the required
expression is used, or completely in extended format[...]
The statement of B. Bourque that java.time has a bug is based on the same wrong expectation about ISO-compatibility. And the documentation of let's say ISO_OFFSET_DATE_TIME describes the support of the extended ISO-format only. See also the related JDK issue. Not all ISO-8601-variants are directly supported hence a pattern-based construction of the parser in the right way is okay.
if offset +0000 try this
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSX" )
LocalDate from =LocalDate.parse("2018-02-13T10:20:12.120+0000",f);

Date formatting exception

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.

Convert date or calendar type into string format

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.

How to get Date pattern from Timezone of Locale in Java

I have a timezone, and Locale of the user. Now I want to get the date pattern.
For example: User's timezone PST and Locale US and the pattern I expect is "MM/dd/yyyy" and if the user's timezone is IST and Locale India, then pattern I expect is "dd/MM/yyyy"
How to get this?
Note: I want to get the pattern not the actual date so that I can use this in some other place.
The logic translating Locale to date/time formats is burried in java.text.SimpleDateFormat#SimpleDateFormat constructor, precisely in sun.util.resources.LocaleData#getDateFormatData. This method provides ResourceBundle which is then queried for particular pattern depending on which style was chosen.
In other words - unfortunately JDK doesn't seems to provide an API/SPI to access raw formats. My advice is to use the Locale all along and pass it to formatting/parsing methods.
Really do you need the TZ for date pattern? The usual way is having the data pattern in the localized properties file for a locale (or locale_country). I think it is enough.
java.time
The modern solution use the java.time classes that years ago supplanted the terrible legacy classes such as SimpleDateFormat. Specifically replaced by DateTimeFormatter.
Skip the formatting pattern, let java.time localize automatically
You asked:
I have a timezone, and Locale of the user. Now I want to get the date pattern.
There is no need to actually obtain the formatting pattern used by a particular locale.
The .ofLocalized… methods on DateTimeFormatter return a formatter object that can automatically localize the text representing the the date-time object’s value. So you don't need to see the pattern, just ask for generated textual result.
The FormatStyle object controls how long or abbreviated the text. The Locale determines the human language and cultural norms to use in localizing.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f =
DateTimeFormatter
.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( locale )
;
String output = zdt.format( f ) ;
Dump to console.
System.out.println( zdt.toInstant().toString() ) ; // Adjust to UTC.
System.out.println( zdt.toString() ) ; // Generate text in standard ISO 8601 format extended wisely to append the name of the time zone in square brackets.
System.out.println( output ) ; // Automatically formatted content.
See this code run live at IdeOne.com.
2020-07-13T23:26:40.554180Z
2020-07-14T08:26:40.554180+09:00[Asia/Tokyo]
mardi 14 juillet 2020 à 08 h 26 min 40 s heure normale du Japon
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
It sounds like you want the static getInstance methods on DateFormat. They take an integer constant for style (short, long, etc.), and optionally a different Locale (instead of the JVM's default).
you can use Interface Map
the k will be Locale
the v will be a string with the date pattern
If you're using Joda Time (and why wouldn't you if you have any choice? It nearly got bundled into JDK 1.7) you could do something like this:
String patternForStyleAndLocale = org.joda.time.format.DateTimeFormat.patternForStyle("S-", locale);
Which unfortunately only gives a two digit year. One work around for that would be:
if (!org.apache.commons.lang.StringUtils.contains(patternForStyleAndLocale, "yyyy"))
{
// The default Joda pattern only has a two digit year for US and Europe, China etc - but we want four digit years
patternForStyleAndLocale = StringUtils.replace(patternForStyleAndLocale, "yy", "yyyy");
}
And you could consider caching them in a ConcurrentHashMap<Locale, String>.
The nice thing about getting a numeric date as a pre-localised pattern like this is that it doesn't require any further localisation later, as it would do if you were using a pattern such as:
"dd MMM yyyy" // UK: "25 Dec 2010" FRANCE: "25 déc. 2010" etc..
However... I just noticed from your later comment that you want to pass the pattern to JavaScript - that might get very difficult since JS uses different pattern formatting to Java (ISO date for instance is "yyyy-MM-dd" in Java and "yy-mm-dd" in JS). I've not tried solving that one but I'd probably use a some string mapping in the JS or Java to simply map from Java patterns to JS. You'd have to know each of the patterns you might encounter for each of the languages in advance of course.

how to convert timestamp string to java.util.Date

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!).

Categories

Resources