Reputation: 1855
Is it possible or are there any method which is automatically convert this type of string to the date object ?
String is = yyyy_mm_ddThh-mm-ss
I need the convert this string to date object because i have to compare with real time. The substring or split may work but i just want to learn is there any special thing or not
EDIT :
From cause of T
in the middle of, simpleDateFormat not working correctly from my side.
SOLVED :
I forget to put '
before and after the T
SimpleDateFormat("yyyy_mm_dd'T'hh-mm-ss");
Upvotes: 1
Views: 131
Reputation: 338326
Joda-Time provides built-in formatters for a variety of such ISO 8601 formats. So you need not even bother with creating that format string.
See this class:
http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html
I learned you don't even need the formatter with Joda-Time 2.3.
Your string is almost in ISO 8601 format. Replace those underscores with hyphens.
The constructor of DateTime accepts a string in ISO 8601 format.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
DateTime dateTime = new DateTime( "2001-02-03T04:05:06", DateTimeZone.UTC );
System.out.println( "dateTime: " + dateTime.toString() );
When run…
dateTime: 2001-02-03T04:05:06.000Z
By the way, your question fails to address the issue of time zones. My example code assumes you meant UTC/GMT (no time zone offset). If you meant otherwise, you should say so. Date-time work should always be explicit about time zones rather than rely on defaults.
Upvotes: 0
Reputation: 71
You need to parse the String with the date format like this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd'T'hh-mm-ss");
Date date;
try {
date = sdf.parse(sdf1.format(dateX) + " " + time);
} catch (ParseException e) {
e.printStackTrace();
}
Upvotes: 0
Reputation: 21961
You need to skip T
with single quotation 'T'
. Also note that, small 'm'
is the format of minute. Use capital 'M'
for month format. Try,
DateFormat df=new SimpleDateFormat("yyyy_MM_dd'T'hh-mm-ss");
System.out.println(df.format(new Date()));
For details, read this documentation of SimpleDateFormat
Upvotes: 2