How to parse time from date string retrieved from Facebook - java

I'm getting these times from Facebook events. E.g: start_time and it's a string like this:
2013-12-21T18:30:00+0100
Now I just want the time, like:
18.30
I tried to do it with this:
SimpleDateFormat formatter = new SimpleDateFormat(" EEEE, dd MMMM yyyy", java.util.Locale.getDefault());
Date formatted = null;
try {
formatted = formatter.parse(p.getStart_time());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String formattedString = formatted.toString();
txtStart_time.setText(""+formattedString);
p.getStart_time() is a String that gives me the date like I said before.
If I do this method, I get an error:
Unparseable date.
Does anybody know a work around?

You need two formats: one to parse the date and one to format it
String startTime = "2013-12-21T18:30:00+0100";
SimpleDateFormat incomingFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date date = incomingFormat.parse(startTime);
SimpleDateFormat outgoingFormat = new SimpleDateFormat(" EEEE, dd MMMM yyyy", java.util.Locale.getDefault());
System.out.println(outgoingFormat.format(date));
prints
Saturday, 21 December 2013

I'm getting these times from Facebook events. E.g: start_time and it's
a string like this:
2013-12-21T18:30:00+0100
Now I just want the time, like:
18.30
Solution using java.time, the modern date-time API:
OffsetDateTime.parse(
"2013-12-21T18:30:00+0100",
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssZ")
).toLocalTime()
Description: Your date-time string has a timezone offset of +01:00 hours. java.time API provides you with OffsetDateTime to contain the information of date-time units along with the timezone offset. Using the applicable DateTimeFormatter, parse the string into an OffsetDateTime and then get the LocalTime part of this date-time using OffsetDateTime#toLocalTime.
Demo using java.time API:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
System.out.println(OffsetDateTime.parse(
"2013-12-21T18:30:00+0100",
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssZ")
).toLocalTime());
}
}
Output:
18:30
ONLINE DEMO
Note: You can use y instead of u here but I prefer u to y.
Learn more about the modern Date-Time API from Trail: Date Time.
A note about the legacy API:
The question and the accepted answer use java.util.Date and SimpleDateFormat which was the correct thing to do in 2013. In Mar 2014, the java.util date-time API and their formatting API, SimpleDateFormat were supplanted by the modern date-time API. Since then, it is highly recommended to stop using the legacy date-time API.

Use something like yyyy-MM-dd'T'HH:mm:ssZ as parsing format instead of EEEE, dd MMMM yyyy.

Substring
If all you want is literally the time component lifted from that string, call the substring method on the String class…
// © 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.*;
String dateTimeStringFromFacebook = "2013-12-21T18:30:00+0100";
// Extract a substring.
String timeSubstring = dateTimeStringFromFacebook.substring( 11, 19 );
DateTime Object
If you want the time converted to a particular time zone, convert the string to a date-time object. Use a formatter to express just the time component.
Here is some example code using the Joda-Time 2.3 library. Avoid the notoriously bad java.util.Date/Calendar classes. Use either Joda-Time or the new java.time.* JSR 310 classes bundled with Java 8.
// From String to DateTime object.
DateTime dateTime = new DateTime( dateTimeStringFromFacebook, DateTimeZone.UTC );
// From DateTime object to String
// Extract just the hours, minutes, seconds.
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm:ss");
String timeFragment_Paris = formatter.withZone( DateTimeZone.forID( "Europe/Paris" ) ).print( dateTime );
String timeFragment_Kolkata = formatter.withZone( DateTimeZone.forID( "Asia/Kolkata" ) ).print( dateTime ); // Formerly known as Calcutta, India.
Dump to console…
System.out.println( "dateTimeStringFromFacebook: " + dateTimeStringFromFacebook );
System.out.println( "timeSubstring: " + timeSubstring );
System.out.println( "dateTime: " + dateTime );
System.out.println( "timeFragment_Paris: " + timeFragment_Paris );
System.out.println( "timeFragment_Kolkata: " + timeFragment_Kolkata + " (Note the 00:30 difference due to +05:30 offset)");
When run…
dateTimeStringFromFacebook: 2013-12-21T18:30:00+0100
timeSubstring: 18:30:00
dateTime: 2013-12-21T17:30:00.000Z
timeFragment_Paris: 18:30:00
timeFragment_Kolkata: 23:00:00 (Note the 00:30 difference due to +05:30 offset)
Think Time Zone
Your question fails to address the question of time zone. Make a habit of always thinking about time zone whenever working with date-time values. If you mean the same time zone, say so explicitly. If you mean the default time zone of the Java environment, say so. If you mean UTC… well, you get the idea.

Related

How to format LocalDate to ISO 8601 with T and Z?

I'm trying to generate a random date and time, and convert it to the "yyyy-MM-dd'T'HH:mm:ss'Z'" format.
Here is what I have tried:
public static String generateRandomDateAndTimeInString() {
LocalDate date = LocalDate.now().minus(Period.ofDays((new Random().nextInt(365 * 70))));
System.out.println("date and time :: " + date.toString());
return formatDate(date) ;
}
public static String formatDate(LocalDate date){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
return dateFormat.format(date);
}
But in the line dateFormat.format(date), it complains with:
java.lang.IllegalArgumentException: Cannot format given Object as a Date
The second problem is that, the output of print does not contain the time:
date :: 1998-12-24
I don't know how to get it to work.
Never format the java.time types using SimpleDateFormat
Using the SimpleDateFormat, you are supposed to format only legacy date-time types e.g. java.util.Date. In order to format the java.time date-time types, you need to use DateTimeFormatter.
Never enclose Z within single quotes
It's a blunder to enclose Z within single quotes in a format. The symbol Z stands for zulu and specifies UTC+00:00. If you enclose it within single quotes, it will simply mean character literal, Z and won't function as UTC+00:00 on parsing.
You do not need to use a formatter explicitly
For this requirement, you do not need to use a formatter explicitly because the OffsetDateTime#toString already returns the string in the format that you need. However, if the number of seconds in an OffsetDateTime object is zero, the same and the subsequent smaller units are truncated by OffsetDateTime#toString. If you need the full format irrespective of the value of seconds, then, of course, you will have to use DateTimeFormatter.
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Random;
public class Main {
public static void main(String[] args) {
System.out.println(generateRandomDateAndTimeInString());
}
public static String generateRandomDateAndTimeInString() {
LocalDate date = LocalDate.now().minus(Period.ofDays((new Random().nextInt(365 * 70))));
System.out.println("date and time :: " + date.toString());
return formatDate(date);
}
public static String formatDate(LocalDate date) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssX");
// return date.atStartOfDay().atOffset(ZoneOffset.UTC).toString();
return date.atStartOfDay().atOffset(ZoneOffset.UTC).format(dtf);
}
}
A sample run:
date and time :: 1996-09-05
1996-09-05T00:00:00Z
Note that the date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Learn more about the modern date-time API from Trail: Date Time.
If you still need to use SimpleDateFormat for whatsoever reason:
Convert LocalDate to ZonedDateTime with ZoneOffset.UTC and at the start of the day ➡️ Convert ZonedDateTime to Instant ➡️ Obtain java.util.Date object from Instant.
public static String formatDate(LocalDate date) {
Date utilDate = Date.from(date.atStartOfDay(ZoneOffset.UTC).toInstant());
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
return dateFormat.format(utilDate);
}
If you want to ignore the time part then you can use ZonedDateTime like this:
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
return ZonedDateTime.of(
date,
LocalTime.MIN,
ZoneId.of("Europe/Paris")
).format(dateFormat);
Output example
2013-10-19T00:00:00+0200
Or much better, you can use just toString to get a formatted date as a String with the default format of ZonedDateTime:
return ZonedDateTime.of(
date,
LocalTime.MIN,
ZoneId.of("Europe/Paris")
).toString();
Output
2013-10-19T00:00+02:00[Europe/Paris]
Note
This date are always with 00:00:00 for time part, because we are using LocalTime.MIN
Also, you can change the ZoneId to the expected Zone, this was just an example.
Important
DateFormat and SimpleDateFormat are legacy library, so please don't mix them with the java.time library, in the top you are using LocalDate which mean you are using this java.time library so keep going with it in all your code.
ZoneOffset utc = ZoneOffset.UTC;
LocalDate today = LocalDate.now(utc);
LocalDate seventyYearsAgo = today.minusYears(70);
int totalDays = Math.toIntExact(ChronoUnit.DAYS.between(seventyYearsAgo, today));
LocalDate date = today.minusDays(new Random().nextInt(totalDays));
String dateString = date.atStartOfDay(utc).toString();
System.out.println("date and time :: " + dateString);
Example output:
date and time :: 1983-08-24T00:00Z
Points to note:
Let java.time convert from years to days. It gives more readable and more correct code (a year is not always 365 days).
To have time of day and UTC offset in the string, convert a ZonedDateTime or an OffsetDateTime since such objects hold time of day and offset. A LocalDate does not. It’s a date without time of day and without offset from UTC. The Z you asked for denotes an offset of 0 from UTC.
If you want hours, minutes and seconds in the output too, you can have that by counting seconds rather than days. In this case use OffsetDateTime for the entire operation (or ZonedDateTime if in a time zone different from UTC).
ZoneOffset utc = ZoneOffset.UTC;
OffsetDateTime today = OffsetDateTime.now(utc).truncatedTo(ChronoUnit.SECONDS);
OffsetDateTime seventyYearsAgo = today.minusYears(70);
long totalSeconds = ChronoUnit.SECONDS.between(seventyYearsAgo, today);
OffsetDateTime date = today.minusSeconds(ThreadLocalRandom.current().nextLong(0, totalSeconds));
String dateString = date.toString();
System.out.println("date and time :: " + dateString);
date and time :: 1996-09-21T06:49:56Z
I am using ThreadLocalRandom because it can generate a random long value in a specified interval. Funnily ThreadLocalRandom has a lot of convenient methods that Random hasn’t got.

Wrong value for hour, minutes and mills when parsing date string to "yyyy-MM-dd'T'HH:mm:ss'-'hh:mm"

I've been experimenting with different formats for a while now. But I encountered a problem when parsing a date string to a date.
Here's the sample date string I'm trying to parse. "2015-04-13T10:17:00-04:00"
Here's my code:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'-'hh:mm", Locale.ENGLISH);
try {
startCal.setTime(format.parse(data.StartTime));
endCal.setTime(format.parse(data.EndTime));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The value that I'm getting when printing it on the log is
Log.i("Event exact date", String.valueOf(startCal.getTime().toString()));
04-13 22:38:11.526: I/Event exact date(1665): Mon Apr 13 04:00:00 GMT+08:00 2015
I was expecting the hour value to be 10 and minutes to be 17. I think it is getting the value from the "-hh:mm". I'm getting this value from a web api. Any ideas guys? Thanks
I think the format you want is:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.ENGLISH);
Where the 'XXX', according to SimpleDateFormat API docs, means ISO 8601 time zone.
Full example:
public class TestDateParse {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.ENGLISH);
Date date = format.parse("2015-04-13T10:17:00-04:00");
System.out.println("date: " + date);
}
}
Test output:
date: Mon Apr 13 16:17:00 CEST 2015
If you not need "-04:00" zone offset (timezone) then just truncate string "2015-04-13T10:17:00-04:00" to "2015-04-13T10:17:00"
String fullDate = "2015-04-13T10:17:00-04:00";
String truncatedDate = fullDate.substring(0, fullDate.lastIndexOf('-'));
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",
Locale.ENGLISH);
try {
Date dte = format.parse(truncatedDate);
System.out.println("date=" + dte);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Result is:
date=Mon Apr 13 10:17:00 CEST 2015
use Z for timezone. It should work.
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
for reference, this is the documentation http://developer.android.com/reference/java/text/SimpleDateFormat.html
java.time
You are using troublesome old date-time classes. Avoid them.
Use the java.time framework built into Java 8 and later. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. Look for back-ports for Java 6 & 7 and for Android.
Your input string happens to be in standard ISO 8601 format. The java.time classes use ISO 8601 as their defaults when parsing/generating textual representations of date-time values. So no need to specify a formatting pattern.
Offset
That last part -04:00 is indeed an offset-from-UTC as mentioned in other Answers. It means the date-time shown is four hours behind UTC.
String input = "2015-04-13T10:17:00-04:00";
OffsetDateTime odt = OffsetDateTime.parse( input );
Time Zone
You can search the list of time zones to see which zones use that particular offset of -04:00. I see a few dozen zones with that offset.
If you know the intended time zone, apply it (a ZoneId). A time zone is an offset-from-UTC plus the rules for handling anomalies such as Daylight Saving Time (DST). So using a time zone is always better than a mere offset, provided you are certain of the correct zone.
ZoneId zoneId = ZoneId.of( "America/Puerto_Rico" );
ZonedDateTime zdt = odt.atZoneSameInstant( zoneId );
UTC
The OffsetDateTime and ZonedDateTime objects seen above represent the very same moment on the timeline. If you want to see that moment in UTC, as for an Instant.
Instant instant = odt.toInstant(); // …or…
Instant instant = zdt.toInstant(); // Both instants are the same moment on the timeline in UTC.

Add colon to 24 hour time in Java?

I have a date in the format MM/DD/YYYY and time in the format HHMM (24 hour time w/o the colon). Both of these strings are in an array. I would like to store this as one string - maybe something like "MM-DD-YYYY HH:MM" - and then be able to convert it to a written date like "January 1, 2014 16:15" when I am showing it to the user. How can I do this?
This is the code that I have:
String date = "05/27/2014 23:01";
Date df = new SimpleDateFormat("MM/DD/YYYY HH:mm").parse(date);
System.out.println(df);
However this is what I get: "Sun Dec 29 23:01:00 EST 2013"
The output I am looking for is: "December 29, 2013 23:01"
SimpleDateFormat is the way to go; to parse your Strings in the required meaningful date and time formats and finally print your date as a required String.
You specify the 2 formats as follows:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");
Considering a simple hardcoded array of date and time (not the best way to show but your question calls it an array):
String[] array = { "12/31/2013", "1230" };
You would have to set these parsed dates in a Calendar instance:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, time.getHours());
cal.add(Calendar.MINUTE, time.getMinutes());
Finally format your date using the same SimpleDateFormat
SimpleDateFormat newFormat = new SimpleDateFormat("MMMM dd, yyyy 'at' hh:mm");
Here is the complete working code:
public class DateExample {
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");
String[] array = { "12/31/2013", "1230" };
try {
Date date = dateFormat.parse(array[0]);
Date time = timeFormat.parse(array[1]);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, time.getHours());
cal.add(Calendar.MINUTE, time.getMinutes());
SimpleDateFormat newFormat = new SimpleDateFormat(
"MMMM dd, yyyy 'at' hh:mm");
String datePrint = newFormat.format(cal.getTime());
System.out.println(datePrint);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The output:
December 31, 2013 at 12:30
Unfortunately, none of the existing answers has mentioned the root cause of the problem which is as follows:
You have used D (which specifies Day in year) instead of d (Day in month).
You have used Y (which specifies Week year) instead of y (Year).
Learn more about it at the documentation page. Now that you have understood the root cause of the problem, let's focus on the solution using the best standard API of the time.
java.time
The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
I would solve it in the following steps:
Parse the date string into LocalDate.
Parse the time string into LocalTime.
Combine the objects of LocalDate and LocalTime to obtain an object of LocalDateTime.
Format the object of LocalDateTime into the desired pattern.
Demo using the modern API:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// 1. Parse the date string into `LocalDate`.
DateTimeFormatter dateParser = DateTimeFormatter.ofPattern("M/d/u", Locale.ENGLISH);
LocalDate date = LocalDate.parse("01/01/2014", dateParser);
// 2. Parse the time string into `LocalTime`.
DateTimeFormatter timeParser = DateTimeFormatter.ofPattern("HHmm", Locale.ENGLISH);
LocalTime time = LocalTime.parse("1615", timeParser);
// 3. Combine date and time to obtain an object of `LocalDateTime`.
LocalDateTime ldt = date.atTime(time);
// 4. Format the object of `LocalDateTime` into the desired pattern.
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("MMMM d, uuuu HH:mm", Locale.ENGLISH);
String output = dtfOutput.format(ldt);
System.out.println(output);
}
}
Output:
January 1, 2014 16:15
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
You can use java.text.DateFormat class to convert date to string(format method), and string to date(parse method).
You can use SimpleDateFormat both to parse Strings into dates and to format Dates back into Strings. Here's your example:
SimpleDateFormat parser = new SimpleDateFormat("MM/DD/YYYY HH:mm");
SimpleDateFormat formatter = new SimpleDateFormat("MMMM dd, yyyy HH:mm");
String dateString = "05/27/2014 23:01";
Date parsedDate = parser.parse(dateString);
String formattedDateString = formatter.format(parsedDate);
System.out.println("Read String '" + dateString + "' as '" + parsedDate + "', formatted as '" + formattedDateString + "'");
When I run this, I get:
Read String '05/27/2014 23:01' as 'Sun Dec 29 23:01:00 EST 2013', formatted as 'December 29, 2013 23:01'
Goal
Convert String to Date with the format you have it in
Output that date as a String in the format you want
Code:
String date = "05/27/2014 23:01";
//convert the String to Date based on its existing format
Date df = new SimpleDateFormat("MM/dd/yyyy HH:mm").parse(date);
System.out.println("date " +df);
//now output the Date as a string in the format you want
SimpleDateFormat dt1 = new SimpleDateFormat("MMMM dd, yyyy HH:mm");
System.out.println(dt1.format(df));
Output:
date Tue May 27 23:01:00 CDT 2014
May 27, 2014 23:01
you can use this >>
String s = sd.format(d);
String s1 = sd1.format(d);
Here Is the full code >>
import java.text.SimpleDateFormat;
import java.util.Date;
public class dt {
public static void main(String[] args) {
// TODO Auto-generated method stub
Date d = new Date();
SimpleDateFormat sd = new SimpleDateFormat("MMMM dd, YYYY");
SimpleDateFormat sd1 = new SimpleDateFormat("HH:mm");
String s = sd.format(d);
String s1 = sd1.format(d);
System.out.println(s +" "+ s1);
}
}
You should have bothered to do a bit of searching before posting. StackOverflow.com has many questions and answers like this already.
But for the sake of posterity, here's some example code using the Joda-Time 2.3 library. Avoid the java.util.Date/Calendar classes bundled with Java as they are badly designed and implemented. In Java 8, continue to use Joda-Time or switch to the new java.time.* classes defined by JSR 310: Date and Time API. Those new classes were inspired by Joda-Time but are entirely re-architected.
Joda-Time has many features aimed at formatting output. Joda-Time offers built-in standard (ISO 8601) formats. Some classes render strings with format and language appropriate to the host computer's locale, or you can specify a locale. And Joda-Time lets you define your own funky formats as well. Searching for "joda" + "format" will get you many examples.
// © 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.*;
String input = "05/27/2014" + " " + "23:01";
Parse that string…
// Assuming that string is for UTC/GMT, pass the built-in constant "DateTimeZone.UTC".
// If that string was stored as-is for a specific time zone (NOT a good idea), pass an appropriate DateTimeZone instance.
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "MM/dd/yyyy HH:mm" ).withZone( DateTimeZone.UTC );
DateTime dateTime = formatterInput.parseDateTime( input );
Ideally you would store the values in an appropriate date-time format in a database. If not possible, then store as a string in ISO 8601 format, set to UTC/GMT (no time zone offset).
// Usually best to write out date-times in ISO 8601 format in the UTC time zone (no time zone offset, 'Z' = Zulu).
String saveThisStringToStorage = dateTime.toDateTime( DateTimeZone.UTC ).toString(); // Convert to UTC if not already in UTC.
Do your business logic and storage in UTC generally. Switch to local time zones and localized formatting only in the user-interface portion of your app.
// Convert to a localized format (string) only as needed in the user-interface, using the user's time zone.
DateTimeFormatter formatterOutput = DateTimeFormat.mediumDateTime().withLocale( Locale.US ).withZone( DateTimeZone.forID( "America/New_York" ) );
String showUserThisString = formatterOutput.print( dateTime );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTime: " + dateTime );
System.out.println( "saveThisStringToStorage: " + saveThisStringToStorage );
System.out.println( "showUserThisString: " + showUserThisString );
When run…
input: 05/27/2014 23:01
dateTime: 2014-05-27T23:01:00.000Z
saveThisStringToStorage: 2014-05-27T23:01:00.000Z
showUserThisString: May 27, 2014 7:01:00 PM

String Date Java

// Im new to java programming
I have a String object that represents a date/time in this format : "2013-06-09 14:20:00" (yyyy-MM-dd HH:mm:ss)
I want to convert it to a Date object so i can perform calculations on it but im confused on how to do this.
I tried :
String string = "2013-06-09 14:20:00";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(string);
System.out.println(date);
//Prints Mon Dec 31 00:00:00 GMT 2012
Any help appreciated
Ok so I have now updated my code to as follows i'm getting the correct date/time now when I print the date but is this the correct implementation :
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = "2013-06-09 14:20:00";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(string);
System.out.println(dateFormat.format(date));
//prints 2013-06-09 14:20:00
Thx to everyone that's answered/commented thus far
The format is wrong. Use this instead:
"yyyy-dd-MM HH:mm:ss"
Indeed your last program version is ok, except you don't need to declare the SimpleDateFormat twice. Simply:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = "2013-06-09 14:20:00";
Date date = dateFormat.parse(string);
System.out.println(dateFormat.format(date));
String string = "2013-06-09 14:20:00";
and the DATE object format is "yyyy-dd-MM HH:mm:ss"
You can get Date,Day,month and many more by using Date object which is present in
java.util.Date package , like as follows.
Date d = new Date(string);
This will call constructor of Date object for which you are passing 'string' variable which contains date.
d.getDay(); // retrieve day on that particular day
d.getDate(); // retrieve Date
and many more are avaiable like this.
Using java.util.Date
The answer by zzKozak is correct. Well, almost correct. The example code omits required exception handling. Like this…
java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = "2013-06-09 14:20:00";
Date date = null;
try {
date = dateFormat.parse(string);
} catch ( ParseException e ) {
e.printStackTrace();
}
System.out.println("date: " + dateFormat.format(date));
Don't Use java.util.Date!
Avoid using java.util.Date & Calendar classes bundled with Java. They are notoriously bad in both design and implementation.
Instead use a competent date-time library. In Java that means either:
The third-party open-source Joda-Time
In the forthcoming Java 8, the new java.time.* classes defined by JSR 310 and inspired by Joda-Time.
Time Zone
Your question and code fail to address the issue of time zones. If you ignore time zones, you'll get defaults. That may cause unexpected behaviors when deployed in production. Better practice is to always specify a time zone.
Formatter
If you replace a space with a 'T' per the standard ISO 8601 format, then you can conveniently feed that string directly to a constructor of a Joda-Time DateTime instance.
If you must use that string as-is, then define a formatter to specify that format. You can find many examples of that here on StackOverflow.com.
Example Code
Here is some example code using Joda-Time 2.3, running in Java 7.
I arbitrarily chose a time zone of Montréal.
// © 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.*;
// Specify a time zone rather than rely on default.
// Necessary to handle Daylight Saving Time (DST) and other anomalies.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime = new DateTime( "2013-06-09T14:20:00", timeZone ); // Or pass DateTimeZone.UTC as time zone for UTC/GMT.
System.out.println( "dateTime: " + dateTime );
When run…
dateTime: 2013-06-09T14:20:00.000-04:00

How to convert date in to yyyy-MM-dd Format?

Sat Dec 01 00:00:00 GMT 2012
I have to convert above date into below format
2012-12-01
How can i?
i have tried with following method but its not working
public Date ConvertDate(Date date){
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String s = df.format(date);
String result = s;
try {
date=df.parse(result);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
Use this.
java.util.Date date = new Date("Sat Dec 01 00:00:00 GMT 2012");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String format = formatter.format(date);
System.out.println(format);
you will get the output as
2012-12-01
String s;
Format formatter;
Date date = new Date();
// 2012-12-01
formatter = new SimpleDateFormat("yyyy-MM-dd");
s = formatter.format(date);
System.out.println(s);
UPDATE My Answer here is now outdated. The Joda-Time project is now in maintenance mode, advising migration to the java.time classes. See the modern solution in the Answer by Ole V.V..
Joda-Time
The accepted answer by NidhishKrishnan is correct.
For fun, here is the same kind of code in Joda-Time 2.3.
// © 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.*;
java.util.Date date = new Date(); // A Date object coming from other code.
// Pass the java.util.Date object to constructor of Joda-Time DateTime object.
DateTimeZone kolkataTimeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeInKolkata = new DateTime( date, kolkataTimeZone );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy-MM-dd");
System.out.println( "dateTimeInKolkata formatted for date: " + formatter.print( dateTimeInKolkata ) );
System.out.println( "dateTimeInKolkata formatted for ISO 8601: " + dateTimeInKolkata );
When run…
dateTimeInKolkata formatted for date: 2013-12-17
dateTimeInKolkata formatted for ISO 8601: 2013-12-17T14:56:46.658+05:30
Modern answer: Use LocalDate from java.time, the modern Java date and time API, and its toString method:
LocalDate date = LocalDate.of(2012, Month.DECEMBER, 1); // get from somewhere
String formattedDate = date.toString();
System.out.println(formattedDate);
This prints
2012-12-01
A date (whether we’re talking java.util.Date or java.time.LocalDate) doesn’t have a format in it. All it’s got is a toString method that produces some format, and you cannot change the toString method. Fortunately, LocalDate.toString produces exactly the format you asked for.
The Date class is long outdated, and the SimpleDateFormat class that you tried to use, is notoriously troublesome. I recommend you forget about those classes and use java.time instead. The modern API is so much nicer to work with.
Except: it happens that you get a Date from a legacy API that you cannot change or don’t want to change just now. The best thing you can do with it is convert it to java.time.Instant and do any further operations from there:
Date oldfashoinedDate = // get from somewhere
LocalDate date = oldfashoinedDate.toInstant()
.atZone(ZoneId.of("Asia/Beirut"))
.toLocalDate();
Please substitute your desired time zone if it didn’t happen to be Asia/Beirut. Then proceed as above.
Link: Oracle tutorial: Date Time, explaining how to use java.time.
You can't format the Date itself. You can only get the formatted result in String. Use SimpleDateFormat as mentioned by others.
Moreover, most of the getter methods in Date are deprecated.
A date-time object is supposed to store the information about the date, time, timezone etc., not about the formatting. You can format a date-time object into a String with the pattern of your choice using date-time formatting API.
The date-time formatting API for the modern date-time types is in the package, java.time.format e.g. java.time.format.DateTimeFormatter, java.time.format.DateTimeFormatterBuilder etc.
The date-time formatting API for the legacy date-time types is in the package, java.text e.g. java.text.SimpleDateFormat, java.text.DateFormat etc.
Demo using modern API:
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
ZonedDateTime zdt = ZonedDateTime.of(LocalDate.of(2012, Month.DECEMBER, 1).atStartOfDay(),
ZoneId.of("Europe/London"));
// Default format returned by Date#toString
System.out.println(zdt);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
String formattedDate = dtf.format(zdt);
System.out.println(formattedDate);
}
}
Output:
2012-12-01T00:00Z[Europe/London]
2012-12-01
Learn about the modern date-time API from Trail: Date Time.
Demo using legacy API:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTimeInMillis(0);
calendar.set(Calendar.YEAR, 2012);
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date date = calendar.getTime();
// Default format returned by Date#toString
System.out.println(date);
// Custom format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
}
}
Output:
Sat Dec 01 00:00:00 GMT 2012
2012-12-01
Some more important points:
The java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the milliseconds from the Epoch of January 1, 1970. When you print an object of java.util.Date, its toString method returns the date-time calculated from this milliseconds value. Since java.util.Date does not have timezone information, it applies the timezone of your JVM and displays the same. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFomrat and obtain the formatted string from it.
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Categories