Convert String to java.util.Date
When I retrieve the date with that format I am get every thing fine except the hour. The hour is always 00 . Here is my output:
String date--->29-Apr-2010,13:00:14 PM After convrting Date--->1272479414000--Thu Apr 29 00:00:14 GMT+05:30 2010
Date lScheduledDate = CalendarObj.getTime(); DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa"); SomeClassObj.setTime(formatter.format(lScheduledDate)); String lNextDate = SomeClassObj.getTime(); DateFormat lFormatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa"); Date lNextDate = (Date)lFormatter.parse(lNextDate); System.out.println("output here"+lNextDate);
Okay buddies Problem solved, problem with the AM/PM «letter aaa» in format, as I am using ‘HH’, ‘aaa’ should not be used, if you use ‘aaa’ then specify ‘hh’
While in 2010, java.util.Date was the class we all used (toghether with DateFormat and Calendar ), for anyone popping by in 2017 or later, those classes are now long outdated. Today one would use the classes in the java.time package, for example LocalDateTime and DateTimeFormatter . There are numerous answers on Stack Overflow to show you how. Go search.
4 Answers 4
I think your date format does not make sense. There is no 13:00 PM. Remove the «aaa» at the end of your format or turn the HH into hh.
Nevertheless, this works fine for me:
String testDate = "29-Apr-2010,13:00:14 PM"; DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa"); Date date = formatter.parse(testDate); System.out.println(date);
It prints «Thu Apr 29 13:00:14 CEST 2010».
You declare your date format and then call the parse method with your string.
private static final DateFormat DF = new SimpleDateFormat(. ); Date myDate = DF.parse("1234");
And as Guillaume says, set the timezone!
Not related but DateFormat objects are not thread safe, they should not be declared static because it makes it more likely that they will be accessed from different threads at some point.
You should set a TimeZone in your DateFormat, otherwise it will use the default one (depending on the settings of the computer).
Your date string doesn’t have time zone info so the z letter won’t help, use setTimeZone(. ) on the SimpleDateFormat object instead
java.time
While in 2010, java.util.Date was the class we all used (toghether with DateFormat and Calendar ), those classes were always poorly designed and are now long outdated. Today one would use java.time, the modern Java date and time API.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy,HH:mm:ss"); String dateTimeStringFromSqlite = "29-Apr-2010,13:00:14"; LocalDateTime dateTime = LocalDateTime.parse(dateTimeStringFromSqlite, formatter); System.out.println("output here: " + dateTime);
What went wrong in your code?
The combination of uppercase HH and aaa in your format pattern strings does not make much sense since HH is for hour of day, rendering the AM/PM marker from aaa superfluous. It should not do any harm, though, and I have been unable to reproduce the exact results you reported. In any case, your comment is to the point no matter if one uses the old-fashioned SimpleDateFormat or the modern DateTimeFormatter :
‘aaa’ should not be used, if you use ‘aaa’ then specify ‘hh’
Lowercase hh is for hour within AM or PM, from 01 through 12, so would require an AM/PM marker.
- In your database, since I understand that SQLite hasn’t got a built-in datetime type, use the standard ISO 8601 format and store time in UTC, for example 2010-04-29T07:30:14Z (the modern Instant class parses and formats such strings as its default, that is, without any explicit formatter).
- Don’t use an offset such as GMT+05:30 for time zone. Prefer a real time zone, for example Asia/Colombo, Asia/Kolkata or America/New_York.
- If you wanted to use the outdated DateFormat , its parse method returns a Date , so you don’t need the cast in Date lNextDate = (Date)lFormatter.parse(lNextDate); .
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
- Oracle tutorial: Date Time explaining how to use java.time .
- Java Specification Request (JSR) 310, where java.time was first described.
- ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
- ThreeTenABP, Android edition of ThreeTen Backport
- Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
- Wikipedia article: ISO 8601
How to convert string to date object?
A Date does not have a format. If you want it formatted in some way, use a DateFormat object. Incidentally, that’s also the way to parse that String into a Date object.
You can’t do that without changing the format. Perhaps you’re plain printing a java.util.Date object which would only result in Date#toString() being shown? (which indeed has a different and fixed format). You should then first convert Date to String in order to display it in the desired format to humans.
5 Answers 5
Here simple code for this:
private Date parseDate(String date) < SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.S'Z'"); Date dateObj = new Date(); try < dateObj = curFormater.parse(date); >catch (ParseException e) < e.printStackTrace(); >return dateObj; >
Use the Time class and parse the string. Then use the Time toMillis() function and instantiate a Date.
From the documentation. Time : This class was deprecated in API level 22. Use GregorianCalendar instead. Check out my answer
This class converts Strings to Dates and vice versa, using a given pattern.
Once you have created a SimpleDateFormat with the right pattern, you can use it to convert the string to a Date, use the date as you like, and eventually convert the Date back to a String using that same SimpleDateFormat instance.
EDIT: clarification on time zones
In the question it is not specified wether the given string is a «pure» ISO 8601 date, and in that case whether you need or not to support multiple time zones, if that timezones will be represented as only numbers (+0200 as in RFC 822), numbers with a colon (+02:00 as permitted by ISO 8601) or as names (EST etc. ).
In case the string is a pure ISO 8601 String, then SimpleDateFormat will have some problems decoding the time zone. If however it is «always Z» (meaning that timezone data is not meaningful and you can safely ignore it), or uses numbers without colon (like +0200 etc..), or uses time zone names, then SimpleDateFormat can handle it correctly.
Parse String to Date with Different Format in Java
A Date object has no format, it is just a number representing the date. The date can be represented by a String with the format of «yyyy-MM-dd».
10 Answers 10
Take a look at SimpleDateFormat . The code goes something like this:
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd"); try < String reformattedStr = myFormat.format(fromUser.parse(inputString)); >catch (ParseException e)
But parse gives me in date format as Fri Jan 06 00:01:00 EST 2012 but it need in 2012-01-06 date format
@Rachel it is because when you call System.out.println(anyDateObject) the default toString() method is called which has been said to print in that format e.g. Fri Jan 06 00:01:00 EST 2012 . You need to override it to suit your needs.
FYI, the troublesome old date-time classes such as java.util.Date , java.util.Calendar , and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle.
tl;dr
LocalDate.parse( "19/05/2009" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) )
Details
The other Answers with java.util.Date , java.sql.Date , and SimpleDateFormat are now outdated.
LocalDate
The modern way to do date-time is work with the java.time classes, specifically LocalDate . The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter
To parse, or generate, a String representing a date-time value, use the DateTimeFormatter class.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ); LocalDate ld = LocalDate.parse( "19/05/2009" , f );
Do not conflate a date-time object with a String representing its value. A date-time object has no format, while a String does. A date-time object, such as LocalDate , can generate a String to represent its internal value, but the date-time object and the String are separate distinct objects.
You can specify any custom format to generate a String. Or let java.time do the work of automatically localizing.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL ) .withLocale( Locale.CANADA_FRENCH ) ; String output = ld.format( f );
System.out.println( "ld: " + ld + " | output: " + output );
ld: 2009-05-19 | output: mardi 19 mai 2009
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.
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- 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.