I have been developing Android application where I use this code:
Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(d);
I need to get date after 8 hours from current moment, and I want that this date has 24-hours format, but I don't know how I can make it by SimpleDateFormat. I also need that date has DD/MM/YYYY HH:MM:SS format.
for 12-hours format:
SimpleDateFormat simpleDateFormatArrivals = new SimpleDateFormat("hh:mm", Locale.UK);
for 24-hours format:
SimpleDateFormat simpleDateFormatArrivals = new SimpleDateFormat("HH:mm", Locale.UK);
This will give you the date in 24 hour format.
Date date = new Date();
date.setHours(date.getHours() + 8);
System.out.println(date);
SimpleDateFormat simpDate;
simpDate = new SimpleDateFormat("kk:mm:ss");
System.out.println(simpDate.format(date));
Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(d);
HH will return 0-23 for hours.
kk will return 1-24 for hours.
See more here: Customizing Formats
use method setIs24HourView(Boolean is24HourView) to set time picker to set 24 hour view.
Use HH instead of hh in formatter string
tl;dr
The modern approach uses java.time classes.
Instant.now() // Capture current moment in UTC.
.truncatedTo( ChronoUnit.SECONDS ) // Lop off any fractional second.
.plus( 8 , ChronoUnit.HOURS ) // Add eight hours.
.atZone( ZoneId.of( "America/Montreal" ) ) // Adjust from UTC to the wall-clock time used by the people of a certain region (a time zone). Returns a `ZonedDateTime` object.
.format( // Generate a `String` object representing textually the value of the `ZonedDateTime` object.
DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" )
.withLocale( Locale.US ) // Specify a `Locale` to determine the human language and cultural norms used in localizing the text being generated.
) // Returns a `String` object.
23/01/2017 15:34:56
java.time
FYI, the old Calendar and Date classes are now legacy. Supplanted by the java.time classes. Much of java.time is back-ported to Java 6, Java 7, and Android (see below).
Instant
Capture the current moment in UTC with the Instant class.
Instant instantNow = Instant.now();
instant.toString(): 2017-01-23T12:34:56.789Z
If you want only whole seconds, without any fraction of a second, truncate.
Instant instant = instantNow.truncatedTo( ChronoUnit.SECONDS );
instant.toString(): 2017-01-23T12:34:56Z
Math
The Instant class can do math, adding an amount of time. Specify the amount of time to add by the ChronoUnit enum, an implementation of TemporalUnit.
instant = instant.plus( 8 , ChronoUnit.HOURS );
instant.toString(): 2017-01-23T20:34:56Z
ZonedDateTime
To see that same moment through the lens of a particular region’s wall-clock time, apply a ZoneId to get a ZonedDateTime.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
zdt.toString(): 2017-01-23T15:34:56-05:00[America/Montreal]
Generate string
You can generate a String in your desired format by specifying a formatting pattern in a DateTimeFormatter object.
Note that case matters in the letters of your formatting pattern. The Question’s code had hh which is for 12-hour time while uppercase HH is 24-hour time (0-23) in both java.time.DateTimeFormatter as well as the legacy java.text.SimpleDateFormat.
The formatting codes in java.time are similar to those in the legacy SimpleDateFormat but not exactly the same. Carefully study the class doc. Here, HH happens to work identically.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" ).withLocale( Locale.US );
String output = zdt.format( f );
Automatic localization
Rather than hard-coding a formatting pattern, consider letting java.time fully localize the generation of the String text by calling DateTimeFormatter.ofLocalizedDateTime.
And, by the way, be aware that time zone and Locale have nothing to do with one another; orthogonal issues. One is about content, the meaning (the wall-clock time). The other is about presentation, determining the human language and cultural norms used in presenting that meaning to the user.
Instant instant = Instant.parse( "2017-01-23T12:34:56Z" );
ZoneId z = ZoneId.of( "Pacific/Auckland" ); // Notice that time zone is unrelated to the `Locale` used in localizing.
ZonedDateTime zdt = instant.atZone( z );
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH ); // The locale determines human language and cultural norms used in generating the text representing this date-time object.
String output = zdt.format( f );
instant.toString(): 2017-01-23T12:34:56Z
zdt.toString(): 2017-01-24T01:34:56+13:00[Pacific/Auckland]
output: mardi 24 janvier 2017 à 01:34:56 heure avancée de la Nouvelle-Zélande
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….
Joda-Time
Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
Joda-Time makes this kind of work much easier.
// © 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 later = DateTime.now().plusHours( 8 );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd/MM/yyyy HH:mm:ss" );
String laterAsText = formatter.print( later );
System.out.println( "laterAsText: " + laterAsText );
When run…
laterAsText: 19/12/2013 02:50:18
Beware that this syntax uses default time zone. A better practice is to use an explicit DateTimeZone instance.
Try below code
String dateStr = "Jul 27, 2011 8:35:29 PM";
DateFormat readFormat = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss aa");
DateFormat writeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = readFormat.parse( dateStr );
} catch ( ParseException e ) {
e.printStackTrace();
}
String formattedDate = "";
if( date != null ) {
formattedDate = writeFormat.format( date );
}
System.out.println(formattedDate);
Good Luck!!!
Check for various formats.
All u need do is to change the lowercase 'hh' in the pattern to an uppercase letter 'HH'
for Kotlin:
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") val currentDate = sdf.format(Date())
for java:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss") Date currentDate = sdf.format(new Date())
LocalDateTime#plusHours
LocalDateTime is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation.
Use LocalDateTime#plusHours to get a copy of this LocalDateTime with the specified number of hours added.
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// ZoneId.systemDefault() returns the timezone of your JVM. It is also the
// default timezone for date-time type i.e.
// LocalDateTime.now(ZoneId.systemDefault()) is same as LocalDateTime.now().
// Change the timezone as per your requirement e.g. ZoneId.of("Europe/London")
LocalDateTime ldt = LocalDateTime.now(ZoneId.systemDefault());
System.out.println(ldt);
LocalDateTime after8Hours = ldt.plusHours(8);
System.out.println(after8Hours);
// Custom format
DateTimeFormatter dtfTimeFormat24H = DateTimeFormatter.ofPattern("dd/MM/uuuu HH:mm:ss", Locale.ENGLISH);
DateTimeFormatter dtfTimeFormat12h = DateTimeFormatter.ofPattern("dd/MM/uuuu hh:mm:ss a", Locale.ENGLISH);
System.out.println(dtfTimeFormat24H.format(after8Hours));
System.out.println(dtfTimeFormat12h.format(after8Hours));
}
}
Output:
2021-01-07T15:24:52.736612
2021-01-07T23:24:52.736612
07/01/2021 23:24:52
07/01/2021 11:24:52 PM
Learn more about the modern date-time API from Trail: Date Time.
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();
Date currentDateTime = calendar.getTime();
System.out.println(currentDateTime);
// After 8 hours
calendar.add(Calendar.HOUR_OF_DAY, 8);
Date after8Hours = calendar.getTime();
System.out.println(after8Hours);
// Custom formats
SimpleDateFormat sdf24H = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.ENGLISH);
// Change the timezone as per your requirement e.g.
// TimeZone.getTimeZone("Europe/London")
sdf24H.setTimeZone(TimeZone.getDefault());
SimpleDateFormat sdf12h = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a", Locale.ENGLISH);
sdf12h.setTimeZone(TimeZone.getDefault());
System.out.println(sdf24H.format(after8Hours));
System.out.println(sdf12h.format(after8Hours));
}
}
Output:
Thu Jan 07 15:34:10 GMT 2021
Thu Jan 07 23:34:10 GMT 2021
07/01/2021 23:34:10
07/01/2021 11:34:10 PM
Some important notes:
A date-time object is supposed to store the information about 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.
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 in the JVM's timezone, calculated from this milliseconds value. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFormat 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.
You can do it like this:
Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy kk:mm:ss").format(d);
here 'kk:mm:ss' is right answer, I confused with Oracle database, sorry.
Try this...
Calendar calendar = Calendar.getInstance();
String currentDate24Hrs = (String) DateFormat.format(
"MM/dd/yyyy kk:mm:ss", calendar.getTime());
Log.i("DEBUG_TAG", "24Hrs format date: " + currentDate24Hrs);
Related
I am getting date and time as a String TIMESTAMP from MySQL from a server in such a format:
2014-02-15 05:18:08
What I want is to extract the Date in DD-MM-YYYY format and the time in HH:MM:SS AM/PM format. Also the timezone of this timestamp is different and I want it in Indian Timezone(IST).
Remember the timestamp is of String datatype.
Use java.text.SimpleDateFormat and java.util.TimeZone
Which timezone the date string is in? Replace the below UTC timezone with that timezone
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse("2014-02-15 05:18:08");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
sdf2.setTimeZone(TimeZone.getTimeZone("IST"));
String dateStr = sdf2.format(date); // Output: 15-02-2014 10:48:08 AM
Note: In which format the hour is in (24 hour/ 12 hour) in your input string? The above example assumes that it is in 24 hour format because there in no AM/PM info in the input string.
If the input string is also in 12 hour format then your input string should mention AM/PM info also such as 2014-02-15 05:18:08 PM. In that case, modify the sdf to new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a")
========================
Edited: =====================
To answer your next question in comment "How to extract date and time separately"...
SimpleDateFormat sdfDate = new SimpleDateFormat("dd-MM-yyyy");
sdfDate.setTimeZone(java.util.TimeZone.getTimeZone("IST"));
SimpleDateFormat sdfTime = new SimpleDateFormat("hh:mm:ss a");
sdfTime.setTimeZone(java.util.TimeZone.getTimeZone("IST"));
String dateStr = sdfDate.format(date);
String timeStr = sdfTime.format(date);
The accepted answer by Yatendra Goel is correct.
Joda-Time
For fun, here's the same kind of code using the Joda-Time 2.3 library.
Note that Joda-Time is now in maintenance mode. The team advises migration to java.time. See my other Answer for java.time code.
FYI… India is five and a half hours ahead of UTC/GMT. Hence the thirty minute difference in the outputs below.
String input = "2014-02-15 05:18:08";
input = input.replace( " ", "T" ); // Replace space in middle with a "T" to get ISO 8601 format.
// Parse input as DateTime in UTC/GMT.
DateTime dateTimeUtc = new DateTime( input, DateTimeZone.UTC );
// Adjust to India time.
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTime = dateTimeUtc.withZone( timeZone );
// Using "en" for English here because (a) it is irrelevant in our case, and (b) I don't know any Indian language codes.
java.util.Locale localeIndiaEnglish = new Locale( "en", "IN" ); // ( language code, country code );
DateTimeFormatter formatter = DateTimeFormat.forStyle( "SS" ).withLocale( localeIndiaEnglish ).withZone( timeZone );
String output = formatter.print( dateTime );
DateTimeFormatter formatterDateOnly = DateTimeFormat.forPattern( "dd-MM-yyyy" ).withLocale( localeIndiaEnglish ).withZone( timeZone );
DateTimeFormatter formatterTimeOnly = DateTimeFormat.forPattern( "hh:mm:ss a" ).withLocale( localeIndiaEnglish ).withZone( timeZone );
String dateOnly = formatterDateOnly.print( dateTime );
String timeOnly = formatterTimeOnly.print( dateTime );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTime: " + dateTime );
System.out.println( "output: " + output );
System.out.println( "dateOnly: " + dateOnly );
System.out.println( "timeOnly: " + timeOnly );
When run…
input: 2014-02-15T05:18:08
dateTimeUtc: 2014-02-15T05:18:08.000Z
dateTime: 2014-02-15T10:48:08.000+05:30
output: 15/2/14 10:48 AM
dateOnly: 15-02-2014
timeOnly: 10:48:08 AM
Use a SimpleDateFormat like:-
String s = new java.text.SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(yourTimestamp);
For more info
SimpleDateFormat.
tl;dr
ZonedDateTime zdt = LocalDateTime.parse( "2014-02-15 05:18:08".replace( " " , "T" ) ).atOffset( ZoneOffset.UTC ).atZoneSameInstant( ZoneId.of( "Asia/Kolkata" ) ) ;
LocalDate ld = zdt.toLocalDate();
LocalTime lt = zdt.toLocalTime();
Use objects, not strings
You should be retrieving date-time values from your database as date-time objects rather than Strings.
As of JDBC 4.2 and later, we can exchange java.time objects with the database.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
myPreparedStatement.setObject( … , instant ) ;
Retrieval.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
java.time
The java.time classes in Java 8 and later supplant the troublesome old legacy date-time classes as well as the 3rd-party Joda-Time library.
The java.sql.Timestamp class is replaced by Instant.
The java.sql.Date class is replaced by LocalDate.
The java.sql.Time class is replaced by LocalTime.
-
Parsing String
If you are stuck with such a String, parse it using a java.time classes. The other Answers are using the troublesome old date-time classes bundled with the earliest versions of Java. Those are now legacy, and should be avoided.
Your input string is almost in standard ISO 8601 format. Merely replace the SPACE in the middle with a T.
String input = "2014-02-15 05:18:08".replace( " " , "T" ) ;
LocalDateTime
Parse as a LocalDateTime as the string lacks any info about offset-from-UTC or time zone.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
OffsetDateTime
I will assume the value in your input String was intended to be a moment in UTC time zone. So adjust into UTC.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
ZonedDateTime
You asked for this to be adjusted into the India time zone, which is five and a half hours ahead of UTC.
The atZoneSameInstant means the resulting ZonedDateTime represents the very same simultaneous moment as the OffsetDateTime. The two are different only in that they view that same moment through two different lenses of wall-clock time.
ZoneId z = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = odt.atZoneSameInstant( z );
LocalDate & LocalTime
If you want to work with the date portion and time-of-day portion separately, extract each as a Local….
LocalDate ld = zdt.toLocalDate();
LocalTime lt = zdt.toLocalTime();
Generating String representation
The toString method on the classes all generate a String representation using standard ISO 8601 formats. To use other formats, use the DateTimeFormatter class. Search Stack Overflow for many examples and discussions.
The easiest way is let the class automatically localize for you. Specify a Locale for the desired human language and the desired cultural norms to decide issues such as capitalization, abbreviation, and such.
Locale locale = new Locale( "en" , "IN" ); // English language, India cultural norms.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT ).withLocale( locale );
String output = zdt.format( f );
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.
you can use DATE_FORMAT(date,format).
in your case it'd be something like this:
SELECT DATE_FORMAT(timestamp, '%e-%c-%Y') FROM table WHERE...
-edit: the code above will return your timestamp as : "DD-MM-YYYY".
timestamp being your mySQL field (in other words: column).
for other format options I'd recommend you to have a quick look at:
DATE_FORMAT options
I want to parse a date, which was created with a specific timezone, convert it to a format and return it. The conversion works but the timezone offset is always set to +0000 with the time difference being added/subtracted as necessary. How can I get it to format and keep the offset correct?
I expect this: 2012-11-30T12:08:56.23+07:00
But get this: 2012-11-30T05:08:56.23+00:00
Implementation:
public static final String ISO_8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSZZ";
public static String formatDateToISO8601Standard(Date date) {
DateTime dateTime = new DateTime(date);
DateTimeFormatter df = DateTimeFormat.forPattern(ISO_8601_DATE_FORMAT);
return dateTime.toString(df);
}
Test class:
private static final String DATE_WITH_TIMEZONE = "30 11 2012 12:08:56.235 +0700";
private static final String EXPECTED_DATE_WITH_TIMEZONE = "2012-11-30T12:08:56.23+07:00";
#Test public void testFormattingDateWithSpecificTimezone() throws Exception {
String result = JodaDateUtil.formatDateToISO8601Standard(createDate(DATE_WITH_TIMEZONE));
assertEquals("The date was not converted correctly", EXPECTED_DATE_WITH_TIMEZONE, result); }
private Date createDate(String dateToParse) throws ParseException {
DateTimeFormatter df = DateTimeFormat.forPattern("dd MM yyyy HH:mm:ss.SSS Z");
DateTime temp = df.parseDateTime(dateToParse);
Date date = temp.toDate();
return date; }
Basically, once you parse the date string [in your createDate() method] you've lost the original zone. Joda-Time will allow you to format the date using any zone, but you'll need to retain the original zone.
In your createDate() method, the DateTimeFormatter "df" can return the zone that was on the string. You'll need to use the withOffsetParsed() method. Then, when you have your DateTime, call getZone(). If you save this zone somewhere or somehow pass it to your formatting routine, then you can use it there by creating a DateTimeFormatter "withZone" and specifying that zone as the one you want on the format.
As a demo, here's some sample code in a single method. Hopefully, it'll help change your code the way you want it to run.
public static void testDate()
{
DateTimeFormatter df = DateTimeFormat.forPattern("dd MM yyyy HH:mm:ss.SSS Z");
DateTime temp = df.withOffsetParsed().parseDateTime("30 11 2012 12:08:56.235 +0700");
DateTimeZone theZone = temp.getZone();
Date date = temp.toDate();
DateTime dateTime = new DateTime(date);
DateTimeFormatter df2 = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSZZ");
DateTimeFormatter df3 = df2.withZone(theZone);
System.out.println(dateTime.toString(df2));
System.out.println(dateTime.toString(df3));
}
tl;dr
OffsetDateTime.parse (
"30 11 2012 12:08:56.235 +0700" ,
DateTimeFormatter.ofPattern ( "dd MM uuuu HH:mm:ss.SSS X" , Locale.US )
).toString()
2012-11-30T12:08:56.235+07:00
Details
The accepted Answer is correct. As soon as you convert to a java.util.Date object, you lose time zone information. This is complicated by the fact that java.util.Date::toString confusingly applies a current default time zone when generating the String.
Avoid using these old date-time classes like java.util.Date. They are poorly-designed, confusing, and troublesome. Now legacy, supplanted by the java.time project. So too is the Joda-Time project now supplanted by the java.time classes.
java.time
Parse that input string as a OffsetDateTime object as it includes an offset-from-UTC but lacks a time zone. Call DateTimeFormatter.ofPattern to specify a custom format matching your input string. Pass that formatter object to OffsetDateTime.parse.
String input = "30 11 2012 12:08:56.235 +0700" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "dd MM uuuu HH:mm:ss.SSS X" , Locale.US );
OffsetDateTime odt = OffsetDateTime.parse ( input , f );
odt:toString(): 2012-11-30T12:08:56.235+07:00
To see the same moment in UTC, extract an Instant. 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 = odt.toInstant();
instant.toString(): 2012-11-30T05:08:56.235Z
You can apply any time zone through which you want to view the same moment, the same point on the timeline.
ZonedDateTime zdtKolkata = odt.toInstant ().atZone ( ZoneId.of ( "Asia/Kolkata" ) );
zdtKolkata.toString(): 2012-11-30T10:38:56.235+05:30[Asia/Kolkata]
No need to mix in the old date-time classes at all. Stick with java.time. If you must use some old code not yet updated to java.time types, look to new methods added to the old classes to convert to/from java.time.
The equivalent of java.util.Date is Instant, both being a count-since-epoch of 1970-01-01T00:00:00Z in UTC. But beware of data-loss as the java.time classes support nanosecond resolution but the old classes are limited to milliseconds.
java.util.Date utilDate = java.util.Date.from( instant );
Live code
See live working code in IdeOne.com.
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, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
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….
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.
Try this.
ISODateTimeFormat.dateTimeParser().parseDateTime(dateString),
then convert that to the format you desire.
Use the format
val formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSSZZ")
I have seconds since 1970 january 1 UTC (Epoch time).
1320105600
I need to convert that seconds into date and time in below format.
Friday,November 4,2011 5:00,AM
How can I achieve this?
In case you're restricted to legacy java.util.Date and java.util.Calendar APIs, you need to take into account that the timestamps are interpreted in milliseconds, not seconds. So you first need to multiply it by 1000 to get the timestamp in milliseconds.
long seconds = 1320105600;
long millis = seconds * 1000;
This way you can feed it to a.o. the constructor of java.util.Date and finally use SimpleDateFormat to convert a java.util.Date to java.lang.String in the desired date format pattern, if necessary with a predefined time zone (otherwise it would use the system default time zone, which is not GMT/UTC per se and thus the formatted time might be off).
Date date = new Date(millis);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE,MMMM d,yyyy h:mm,a", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String formattedDate = sdf.format(date);
System.out.println(formattedDate); // Tuesday,November 1,2011 12:00,AM
In case you're already on Java8, there's a LocalDateTime#ofEpochSecond() which allows you to feed epoch seconds directly without the need for multiplying into milliseconds flavor.
LocalDateTime dateTime = LocalDateTime.ofEpochSecond(seconds, 0, ZoneOffset.UTC);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE,MMMM d,yyyy h:mm,a", Locale.ENGLISH);
String formattedDate = dateTime.format(formatter);
System.out.println(formattedDate); // Tuesday,November 1,2011 12:00,AM
long yourSeconds = 1320105600L;
Date date = new Date(yourSeconds * 1000);
See this javadoc for more info. The constructor needs milliseconds.
To display this date in an appropriate format you should check DateFormat
Here is an example:
DateFormat df = new SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz");
System.out.println(df.format(date));
java.time
The Answer by BalusC is good in that it points you to using java.time. But that Answer uses LocalDateTime where Instant is more appropriate. A LocalDateTime is not a moment on the timeline as it purposely has no concept of offset-from-UTC or time zone.
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat. The Joda-Time team also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
Instant
A moment on the timeline in UTC with a resolution up to nanoseconds is represented by the Instant class.
Instant instant = Instant.ofEpochSecond ( 1_320_105_600L );
Dump to console. Your input value is the first moment of November 1, 2011 in UTC. The Z on the end, short for 'Zulu', means UTC.
System.out.println ( "instant: " + instant );
instant: 2011-11-01T00:00:00Z
ZonedDateTime
In your comments you mention wanting to see this date-time through the lens of the America/Chicago time zone. Use a proper time zone name. Apply a time zone, ZoneId, to get a ZonedDateTime object. We see that Chicago is five hours behind UTC on that date.
ZoneId zoneId = ZoneId.of ( "America/Chicago" );
ZonedDateTime zdt = instant.atZone ( zoneId );
zdt: 2011-10-31T19:00-05:00[America/Chicago]
Strings
The Strings seen above are in standard ISO 8601 format. To generate strings in other formats, use the DateTimeFormatter class. You can specify your own custom pattern. But generally best to let java.time automatically localize to the human language and cultural norms encoded in a Locale object.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.FULL );
formatter = formatter.withLocale ( Locale.US );
String output = zdt.format ( formatter );
Monday, October 31, 2011 7:00:00 PM CDT
To specify your own custom format, search Stack Overflow for many examples and more discussion.
int seconds = 1320105600;
Date date = new Date(seconds * 1000);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE,MMMM d,yyyy h:mm,a");
System.out.println(sdf.format(date));
The trick is to use java.util.Date and java.text.DateFormat to get the format you want. You can look up how to do it in tutorials on the Web.
I have milliseconds in certain log file generated in server, I also know the locale from where the log file was generated, my problem is to convert milliseconds to date in specified format.
The processing of that log is happening on server located in different time zone. While converting to "SimpleDateFormat" program is taking date of the machine as such formatted date do not represent correct time of the server. Is there any way to handle this elegantly ?
long yourmilliseconds = 1322018752992l;
//1322018752992-Nov 22, 2011 9:25:52 PM
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS",Locale.US);
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("US/Central"));
calendar.setTimeInMillis(yourmilliseconds);
System.out.println("GregorianCalendar -"+sdf.format(calendar.getTime()));
DateTime jodaTime = new DateTime(yourmilliseconds,
DateTimeZone.forTimeZone(TimeZone.getTimeZone("US/Central")));
DateTimeFormatter parser1 = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss,SSS");
System.out.println("jodaTime "+parser1.print(jodaTime));
Output:
Gregorian Calendar -2011-11-23 08:55:52,992
jodaTime 2011-11-22 21:25:52,992
You may use java.util.Date class and then use SimpleDateFormat to format the Date.
Date date=new Date(millis);
We can use java.time package (tutorial) - DateTime APIs introduced in the Java SE 8.
var instance = java.time.Instant.ofEpochMilli(millis);
var localDateTime = java.time.LocalDateTime
.ofInstant(instance, java.time.ZoneId.of("Asia/Kolkata"));
var zonedDateTime = java.time.ZonedDateTime
.ofInstant(instance,java.time.ZoneId.of("Asia/Kolkata"));
// Format the date
var formatter = java.time.format.DateTimeFormatter.ofPattern("u-M-d hh:mm:ss a O");
var string = zonedDateTime.format(formatter);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeStamp);
int mYear = calendar.get(Calendar.YEAR);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
tl;dr
Instant.ofEpochMilli( 1_322_018_752_992L ) // Parse count of milliseconds-since-start-of-1970-UTC into an `Instant`.
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Assign a time zone to the `Instant` to produce a `ZonedDateTime` object.
Details
The other answers use outmoded or incorrect classes.
Avoid the old date-time classes such as java.util.Date/.Calendar. They have proven to be poorly designed, confusing, and troublesome.
java.time
The java.time framework comes built into Java 8 and later. Much of the functionality is backported to Java 6 & 7 and further adapted to Android. Made by the some of the same folks as had made Joda-Time.
An Instant is a moment on the timeline in UTC with a resolution of nanoseconds. Its epoch is first moment of 1970 in UTC.
Assuming your input data is a count of milliseconds from 1970-01-01T00:00:00Z (not clear in the Question), then we can easily instantiate an Instant.
Instant instant = Instant.ofEpochMilli( 1_322_018_752_992L );
instant.toString(): 2011-11-23T03:25:52.992Z
The Z in that standard ISO 8601 formatted string is short for Zulu and means UTC.
Apply a time zone using a proper time zone name, to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( zoneId );
See this code run live at IdeOne.com.
Asia/Kolkata time zone ?
I am guessing your are had an India time zone affecting your code. We see here that adjusting into Asia/Kolkata time zone renders the same time-of-day as you report, 08:55 which is five and a half hours ahead of our UTC value 03:25.
2011-11-23T08:55:52.992+05:30[Asia/Kolkata]
Default zone
You can apply the current default time zone of the JVM. Beware that the default can change at any moment during runtime. Any code in any thread of any app within the JVM can change the current default. If important, ask the user for their desired/expected time zone.
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or 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, 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.
The easiest way to do this is to use the Joda DateTime class and specify both the timestamp in milliseconds and the DateTimeZone you want.
I strongly recommend avoiding the built-in Java Date and Calendar classes; they're terrible.
If the millis value is number of millis since Jan 1, 1970 GMT, as is standard for the JVM, then that is independent of time zone. If you want to format it with a specific time zone, you can simply convert it to a GregorianCalendar object and set the timezone. After that there are numerous ways to format it.
My Solution
public class CalendarUtils {
public static String dateFormat = "dd-MM-yyyy hh:mm";
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
public static String ConvertMilliSecondsToFormattedDate(String milliSeconds){
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(Long.parseLong(milliSeconds));
return simpleDateFormat.format(calendar.getTime());
}
}
Easiest way:
private String millisToDate(long millis){
return DateFormat.getDateInstance(DateFormat.SHORT).format(millis);
//You can use DateFormat.LONG instead of SHORT
}
I do it like this:
static String formatDate(long dateInMillis) {
Date date = new Date(dateInMillis);
return DateFormat.getDateInstance().format(date);
}
You can also use getDateInstance(int style) with following parameters:
DateFormat.SHORT
DateFormat.MEDIUM
DateFormat.LONG
DateFormat.FULL
DateFormat.DEFAULT
The SimpleDateFormat class has a method called SetTimeZone(TimeZone) that is inherited from the DateFormat class. http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html
You can try java.time api;
Instant date = Instant.ofEpochMilli(1549362600000l);
LocalDateTime utc = LocalDateTime.ofInstant(date, ZoneOffset.UTC);
Below is my solution to get date from miliseconds to date format. You have to use Joda Library to get this code run.
import java.util.GregorianCalendar;
import java.util.TimeZone;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class time {
public static void main(String args[]){
String str = "1431601084000";
long geTime= Long.parseLong(str);
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("US/Central"));
calendar.setTimeInMillis(geTime);
DateTime jodaTime = new DateTime(geTime,
DateTimeZone.forTimeZone(TimeZone.getTimeZone("US/Central")));
DateTimeFormatter parser1 = DateTimeFormat.forPattern("yyyy-MM-dd");
System.out.println("Get Time : "+parser1.print(jodaTime));
}
}
public static String getFormatTimeWithTZ(Date currentTime) {
SimpleDateFormat timeZoneDate = new SimpleDateFormat("EEE, dd-MM-yyyy hh:mm a", Locale.getDefault());
return timeZoneDate.format(currentTime);
}
Output is
Mon,01-03-2021 07:37 PM
and
public static String getFormatTimeWithTZ(Date currentTime) {
SimpleDateFormat timeZoneDate = new SimpleDateFormat("EEE, dd-MM-yyyy HH:mm ", Locale.getDefault());
return timeZoneDate.format(currentTime);
}
output is
Mon,01-03-2021 19:37
if you do not want the Days Then Remove EEE,
if you do not want the Date Then Remove dd-MM-yyyy
If you want Time in Hour, Minutes, Second, Millisecond then Use HH:mm:ss.SSS
and Call this method where you want
getFormatTimeWithTZ(Mydate)
where
Date Mydate = new Date(System.currentTimeMillis());
public static LocalDateTime timestampToLocalDateTime(Long timestamp) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), TimeZone.getDefault().toZoneId());
}
I have a String of a date and time like this: 2011-04-15T20:08:18Z. I don't know much about date/time formats, but I think, and correct me if I'm wrong, that's its UTC format.
My question: what's the easiest way to parse this to a more normal format, in Java?
tl;dr
String output =
Instant.parse ( "2011-04-15T20:08:18Z" )
.atZone ( ZoneId.of ( "America/Montreal" ) )
.format (
DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.FULL )
.withLocale ( Locale.CANADA_FRENCH )
)
;
vendredi 15 avril 2011 16 h 08 EDT
Details
The answer by Josh Pinter is correct, but could be even simpler.
java.time
In Java 8 and later, the bundled java.util.Date/Calendar classes are supplanted by the java.time framework defined by JSR 310. Those classes are inspired by Joda-Time but are entirely re-architected.
The java.time framework is the official successor to Joda-Time. The creators of Joda-Time have advised we should migrate to java.time as soon as is convenient. Joda-Time continues to be updated and tweaked, but further innovation will be done only in java.time and its extensions in the ThreeTen-Extra project.
The bulk of java.time functionality has been back-ported to Java 6 & 7 in the ThreeTen-Backport project, and further adapted to Android in ThreeTenABP project.
The equivalent for the Joda-Time code above is quite similar. Concepts are similar. And like Joda-Time, the java.time classes by default use ISO 8601 formats when parsing/generating textual representations of date-time values.
An Instant is a moment on the timeline in UTC with a resolution of nanoseconds (versus milliseconds used by Joda-Time & java.util.Date).
Instant instant = Instant.parse( "2011-04-15T20:08:18Z" );
Apply a time zone (ZoneId) to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Adjust into yet another time zone.
ZoneId zoneId_NewYork = ZoneId.of( "America/New_York" );
ZonedDateTime zdt_NewYork = zdt.withZoneSameInstant( zoneId_NewYork );
To create strings in other formats beyond those of the toString methods, use the java.time.format classes. You can specify your own formatting pattern or let java.time localize automatically. Specify a Locale for (a) the human language used in translation of name of month/day-of-week, and (b) cultural norms for period-versus-comma, order of the parts, and such.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL );
formatter = formatter.withLocale( Locale.US );
String output = zdt_NewYork.format( formatter );
Friday, April 15, 2011 4:08:18 PM EDT
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.
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This section left intact for history.
Pass String To Constructor
Joda-Time can take that string directly. Simply pass to a constructor on the DateTime class.
Joda-Time understands the standard ISO 8601 format of date-times, and uses that format as its default.
Example Code
Here is example code in Joda-Time 2.3 running in Java 7 on a Mac.
I show how to pass the string to a DateTime constructor, in two ways: With and without a time zone. Specifying a time zone solves many problems people encounter in doing date-time work. If left unspecified, you get the default time zone which can bring surprises when placed into production.
I also show how specify no time zone offset (UTC/GMT) using the built-in constant DateTimeZone.UTC. That's what the Z on the end, short for Zulu time, means: No time zone offset (00:00).
// © 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.*;
// Default time zone.
DateTime dateTime = new DateTime( "2011-04-15T20:08:18Z" );
// Specified time zone.
DateTime dateTimeInKolkata = new DateTime( "2011-04-15T20:08:18Z", DateTimeZone.forID( "Asia/Kolkata" ) );
DateTime dateTimeInNewYork = new DateTime( "2011-04-15T20:08:18Z", DateTimeZone.forID( "America/New_York" ) );
// In UTC/GMT (no time zone offset).
DateTime dateTimeUtc = dateTimeInKolkata.toDateTime( DateTimeZone.UTC );
// Output in localized format.
DateTimeFormatter formatter = DateTimeFormat.shortDateTime().withLocale( Locale.US );
String output_US = formatter.print( dateTimeInNewYork );
Dump to console…
System.out.println("dateTime: " + dateTime );
System.out.println("dateTimeInKolkata: " + dateTimeInKolkata );
System.out.println("dateTimeInNewYork: " + dateTimeInNewYork );
System.out.println("dateTimeUtc: " + dateTimeUtc );
System.out.println("dateTime in US format: " + output_US );
When run…
dateTime: 2011-04-15T13:08:18.000-07:00
dateTimeInKolkata: 2011-04-16T01:38:18.000+05:30
dateTimeInNewYork: 2011-04-15T16:08:18.000-04:00
dateTimeUtc: 2011-04-15T20:08:18.000Z
dateTime in US format: 4/15/11 4:08 PM
Use JodaTime
I kept getting parsing errors using the other solutions with the Z at the end of the format.
Instead, I opted to leverage JodaTime's excellent parsing functionality and was able to do the following very easily:
String timestamp = "2011-04-15T20:08:18Z";
DateTime dateTime = ISODateTimeFormat.dateTimeParser().parseDateTime(timestamp);
This correctly recognizes the UTC timezone and allows you to then use JodaTime's extensive manipulation methods to get what you want out of it.
Hope this helps others.
Already has lot of answer but just wanted to update with java 8 in case any one faced issues while parsing string date.
Generally we face two problems with dates
Parsing String to Date
Display Date in desired string format
DateTimeFormatter class in Java 8 can be used for both of these purpose.
Below methods try to provide solution to these issues.
Method 1:
Convert your UTC string to Instant. Using Instant you can create Date for any time-zone by providing time-zone string and use DateTimeFormatter to format date for display as you wish.
String dateString = "2016-07-13T18:08:50.118Z";
String tz = "America/Mexico_City";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a");
ZoneId zoneId = ZoneId.of(tz);
Instant instant = Instant.parse(dateString);
ZonedDateTime dateTimeInTz =ZonedDateTime.ofInstant(instant, zoneId);
System.out.println(dateTimeInTz.format(dtf));
Method 2:
Use DateTimeFormatter built in constants e.g ISO_INSTANT to parse string to LocalDate.
ISO_INSTANT can parse dates of pattern
yyyy-MM-dd'T'HH:mm:ssX e.g '2011-12-03T10:15:30Z'
LocalDate parsedDate
= LocalDate.parse(dateString, DateTimeFormatter.ISO_INSTANT);
DateTimeFormatter displayFormatter = DateTimeFormatter.ofPattern("yyyy MM dd");
System.out.println(parsedDate.format(displayFormatter));
Method 3:
If your date string has much precision of time e.g it captures fraction of seconds as well as in this case 2016-07-13T18:08:50.118Z then method 1 will work but method 2 will not work. If you try to parse it will throw DateTimeException Since ISO_INSTANT formatter will not be able to parse fraction of seconds as you can see from its pattern.
In this case you will have to create a custom DateTimeFormatter by providing date pattern as below.
LocalDate localDate
= LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX"));
Taken from a blog link written by me.
The Java 7 version of SimpleDateFormat supports ISO-8601 time zones using the uppercase letter X.
String string = "2011-04-15T20:08:18Z";
DateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date date = iso8601.parse(string);
If you're stuck with Java 6 or earlier, the answer recommending JodaTime is a safe bet.
You have to give the following format:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date parse = simpleDateFormat.parse( "2011-04-15T20:08:18Z" );
I had a parse error in Andrew White solution.
Adding the single quote around the Z solved the issue
DateFormat m_ISO8601Local = new SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss'Z'");
the pattern in #khmarbaise answer worked for me, here's the utility method I extracted (note that the Z is omitted from the pattern string):
/**
* Converts an ISO-8601 formatted UTC timestamp.
*
* #return The parsed {#link Date}, or null.
*/
#Nullable
public static Date fromIsoUtcString(String isoUtcString) {
DateFormat isoUtcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
isoUtcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return isoUtcFormat.parse(isoUtcString);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
For all the older versions of JDK (6 down) it may be useful.
Getting rid of trailing 'Z' and replacing it literally with 'UTC' timezone display name - then parsing the whole string using proper simple date formatter.
String timeZuluVal = "2011-04-15T20:08:18Z";
timeZuluVal = timeZuluVal.substring( 0, timeZuluVal.length() - 2 ); // strip 'Z';
timeZuluVal += " " + TimeZone.getTimeZone( "UTC" ).getDisplayName();
DateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss zzzz" );
Date dateVal = simpleDateFormat.parse( timeZuluVal );
Joda Time
public static final String SERVER_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static DateTime getDateTimeFromUTC(String time) {
try {
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(SERVER_TIME_FORMAT).withZoneUTC();
Calendar localTime = Calendar.getInstance();
DateTimeZone currentTimeZone = DateTimeZone.forTimeZone(localTime.getTimeZone());
return dateTimeFormatter.parseDateTime(time).toDateTime().withZone(currentTimeZone);
} catch (Exception e) {
return DateTime.now();
}
}