I want to parse a date into my format like 02:09 AM 25/09/2012 but I can't. I used this code.
SimpleDateFormat sdf1 = new SimpleDateFormat("MMMM, DD yyyy HH:mm:ss Z");
//September, 25 2012 02:09:42 +0000
Date date = sdf1.parse(String.valueOf(PUNCH_TIME));
SimpleDateFormat sdf2 = new SimpleDateFormat("HH':'mm a 'on' DD'/'MMMM'/'yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("MM");
String timeformat=sdf2.format(date);
txtHomePunchStatus.setText("You have Punched In at "+timeformat);
and I got You have punched IN at 7:52 AM on 25/01/2012.
You probably have issues with the time zone. The input string September, 25 2012 02:09:42 +0000 is a timestamp in UTC (offset +0000). When you format your date in the desired format, you're not specifying a time zone, so the SimpleDateFormat object is going to show your date in your local time zone, which is probably not UTC.
What you can do is set the time zone on the SimpleDateFormat object that you use to format the date. For example:
DateFormat df1 = new SimpleDateFormat("MMMM, dd yyyy HH:mm:ss Z");
Date date = df1.parse(PUNCH_TIME);
DateFormat df2 = new SimpleDateFormat("HH:mm a 'on' dd/MM/yyyy");
df2.setTimeZone(TimeZone.getTimeZone("UTC"));
String result = df2.format(date);
System.out.println(result);
Note: You must use dd and not DD for the days; DD means day number of the year, dd means day number in the month (see the API documentation of SimpleDateFormat).
p.s.: Your usage of the words "parse" and "format" is confusing. Parsing means: converting from a string to a Date object, and formatting means the opposite: converting from a Date object to a string.
First off you have a double declaration of sdf2. Then, you need to use hh and mm for hours and minutes. Read the documentation: SimpleDateFormat Like in this example:
SimpleDateFormat sdf1 = new SimpleDateFormat("MMMM, DD yyyy HH:mm:ss Z");
//September, 25 2012 02:09:42 +0000
Date date = null;
try {
date = sdf1.parse(String.valueOf(PUNCH_TIME));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SimpleDateFormat sdf2 = new SimpleDateFormat("hh:mm a 'on' DD/MM/yyyy");
String timeformat=sdf2.format(date);
tl;dr
OffsetDateTime.parse(
"September, 25 2012 02:09:42 +0000" ,
DateTimeFormatter.ofPattern( "MMMM, d uuuu HH:mm:ss Z" , Locale.US )
).format(
DateTimeFormatter.ofPattern( "hh:mm a 'on' dd/MM/uuuu" , Locale.US )
)
02:09 AM on 25/09/2012
Avoid legacy date-time classes
The other Answers are now outmoded, using troublesome old date-time classes that are now legacy. The old classes are supplanted by the java.time classes. For earlier Android, see the last bullets below.
java.time
Define a formatting pattern to match your input string.
String input = "September, 25 2012 02:09:42 +0000" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMMM, d uuuu HH:mm:ss Z" , Locale.US ) ; // Specify a locale for the human language by which to parse the name of the month.
Parse as an OffsetDateTime given that your input specifies an offset-from-UTC but not a full time zone.
OffsetDateTime odt = OffsetDateTime odt = OffsetDateTime.parse( input , f );
odt.toString(): 2012-09-25T02:09:42Z
To generate a string in an alternate format, define a DateTimeFormatter with a custom formatting pattern. Pay attention to the uppercase/lowercase of your formatting code characters, and study closely the documentation. Note that colons, spaces, and slashes are known by the formatter, so no need to escape those characters with the single-quote marks.
DateTimeFormatter fOutput = DateTimeFormatter.ofPattern( "hh:mm a 'on' dd/MM/uuuu" , Locale.US ) ;
String output = odt.format( fOutput) ;
02:09 AM on 25/09/2012
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Related
This question already has answers here:
java.text.ParseException: Unparseable date
(10 answers)
Closed 6 years ago.
My date string is: "Wed Oct 19 14:34:26 BRST 2016" and I'm trying to parse it to "dd/MM/yyyy", but I'm getting the following exception:
java.text.ParseException: Unparseable date: "Wed Oct 19 14:34:26 BRST 2016" (at offset 20)
the method
public String dataText(int lastintervalo) {
Date mDate = new Date();
String dt = mDate.toString();
SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
Locale.getDefault());
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(dt));
} catch (ParseException e) {
e.printStackTrace();
}
sdf.applyPattern("dd/MM/yyyy");
c.add(Calendar.DATE, lastintervalo);
return sdf.format(c.getTime());
}
I already searched on google and stackoverflow questions, but nothing seems to work
Since the error message is complaining about offset 20, which is the BRST value, it seems that it cannot resolve the time zone.
Please try this code, that should ensure that the Brazilian time zone is recognized:
SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("America/Sao_Paulo"));
System.out.println(sdf.parse("Wed Oct 19 14:34:26 BRST 2016"));
Since I'm in Eastern US, that prints this for me:
Wed Oct 19 12:34:26 EDT 2016
tl;dr
ZonedDateTime.parse (
"Wed Oct 19 14:34:26 BRST 2016" ,
DateTimeFormatter.ofPattern ( "EE MMM dd HH:mm:ss z uuuu" )
)
.toLocalDate()
.format(
DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT)
.withLocale( Locale.UK )
)
19/10/16
java.time
You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes.
Use real time zone
Never use the 3-4 letter abbreviation such as BRST or EST or IST as they are not true time zones, not standardized, and not even unique(!).
Specify a proper time zone name in the format of continent/region. For example, America/Sao_Paulo.
So while the code below works in this particular case, I do not recommend exchanging data such as your input. If you have influence over the data source, change to using standard ISO 8601 formats for data exchange of date-time values.
2016-10-19T14:34:26-02:00
Even better, exchange strings as created by ZonedDateTime that extend ISO 8601 format by appending the time zone name in square brackets.
2016-10-19T14:34:26-02:00[America/Sao_Paulo]
Best of all, usually, is to convert such values to UTC before exchanging data. In java.time, call toInstant().toString() to do this. Generally best to work in UTC, applying a time zone only where required such as presentation to the user.
2016-10-19T16:34:26Z
Example code
String input = "Wed Oct 19 14:34:26 BRST 2016";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "EE MMM dd HH:mm:ss z uuuu" );
ZonedDateTime zdt = ZonedDateTime.parse ( input , f );
zdt.toString(): 2016-10-19T14:34:26-02:00[America/Sao_Paulo]
To see the same moment in UTC, extract a Instant.
Instant instant = zdt.toInstant();
instant.toString(): 2016-10-19T16:34:26Z
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = zdt.toLocalDate();
ld.toString(): 2016-10-19
To generate strings in other formats, search Stack Overflow for DateTimeFormatter class. Generally best to let java.time localize automatically.
To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such.
Example:
Locale l = Locale.CANADA_FRENCH ; // Or Locale.US or Locale.ITALY etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT).withLocale( l );
String output = ld.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, & 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..It may work
SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
Locale.ENGLISH);
This question already has answers here:
Change date format in a Java string
(22 answers)
Closed 4 years ago.
I am new to Java. I am trying to convert date from string to MMM yyyy format (Mar 2016). I tried this
Calendar cal=Calendar.getInstance();
SimpleDateFormat month_date = new SimpleDateFormat("MMM yyyy");
String month_name = month_date.format(cal.getTime());
System.out.println("Month :: " + month_name); //Mar 2016
It is working fine. But when I use
String actualDate = "2016-03-20";
It is not working. Help me, how to solve this.
Your format must match your input
for 2016-03-20
the format should be (just use a second SimpleDateFormat object)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Full answer
SimpleDateFormat month_date = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String actualDate = "2016-03-20";
Date date = sdf.parse(actualDate);
String month_name = month_date.format(date);
System.out.println("Month :" + month_name); //Mar 2016
Using java.time java-8
String actualDate = "2016-03-20";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("MMM yyyy", Locale.ENGLISH);
DateTimeFormatter dtf3 = DateTimeFormatter.ofPattern("MMMM yyyy", Locale.ENGLISH);
LocalDate ld = LocalDate.parse(actualDate, dtf);
String month_name = dtf2.format(ld);
System.out.println(month_name); // Mar 2016
String fullMonthAndYear = dtf3.format(ld);
System.out.println(fullMonthAndYear); // March 2016
Try this code:
DateFormat df = new SimpleDateFormat("dd-MMMM HH:mm a");
Date date = new Date(System.currentTimeMillis());
String infi = df.format(date);
And the output should be:
11-May 4:47 PM
tl;dr
YearMonth.from(
LocalDate.parse( "2016-03-20" )
)
.format(
DateTimeFormatter.ofPattern(
"MMM uuuu" ,
Locale.US
)
)
Mar 2016
java.time
Avoid the troublesome old date-time classes. Entirely supplanted by the java.time classes.
YearMonth
Java has a class to represent a year and month. Oddly named, YearMonth.
LocalDate ld = LocalDate.parse( "2016-03-20" ) ;
YearMonth ym = YearMonth.from( ld ) ;
Define a formatting pattern for your desired output.
Specify a Locale. A Locale determines (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM uuuu" , Locale.US ) ;
String output = ym.format( f ) ;
Mar 2016
You could use that formatter on the LocalDate. But I assume you may have further need of the year-month as a concept, and so the YearMonth class may be useful.
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.
this is my date " 15-05-2014 00:00:00 "
how to convert IST to UTC i.e( to 14-05-2014 18:30:00)
based on from timezone to UTC timezone.
my code is
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("IST")); //here set timezone
System.out.println(formatter.format(date));
formatter.setTimeZone(TimeZone.getTimeZone("UTC")); //static UTC timezone
System.out.println(formatter.format(date));
String str = formatter.format(date);
Date date1 = formatter.parse(str);
System.out.println(date1.toString());
if user enter same date from any zone then will get UTC time(ex: from Australia then 15-05-2014 00:00:00 to 14-05-2014 16:00:00)
please any suggestions.
You cannot "convert that date values" to other timezones or UTC. The type java.util.Date does not have any internal timezone state and only refers to UTC by spec in a way which cannot be changed by user (just counting the milliseconds since UNIX epoch in UTC timezone leaving aside leapseconds).
But you can convert the formatted String-representation of a java.util.Date to another timezone. I prefer to use two different formatters, one per timezone (and pattern). I also prefer to use "Asia/Kolkata" in your case because then it will universally works (IST could also be "Israel Standard Time" which will be interpreted differently in Israel):
DateFormat formatterIST = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formatterIST.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata")); // better than using IST
Date date = formatterIST.parse("15-05-2014 00:00:00");
System.out.println(formatterIST.format(date)); // output: 15-05-2014 00:00:00
DateFormat formatterUTC = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formatterUTC.setTimeZone(TimeZone.getTimeZone("UTC")); // UTC timezone
System.out.println(formatterUTC.format(date)); // output: 14-05-2014 18:30:00
// output in system timezone using pattern "EEE MMM dd HH:mm:ss zzz yyyy"
System.out.println(date.toString()); // output in my timezone: Wed May 14 20:30:00 CEST 2014
tl;dr
LocalDateTime.parse(
"15-05-2014 00:00:00" ,
DateTimeFormatter.ofPattern( "dd-MM-uuuu HH:mm:ss" )
)
.atZone( ZoneId.of( "Asia/Kolkata" ) )
.toInstant()
java.time
The Answer by Meno Hochschild is correct but shows classes that are now outdated.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( "15-05-2014 00:00:00" , f ) ;
ldt.toString(): 2014-05-15T00:00
Apparently you are certain that string represents a moment in India time. Tip: You should have included the zone or offset in that string. Even better, use standard ISO 8601 formats.
Assign the India time zone.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
zdt.toString(): 2014-05-15T00:00+05:30[Asia/Kolkata]
To see the same moment, the same point on the timeline, through the wall-clock time of UTC, extract an Instant.
Instant instant = zdt.toInstant() ;
instant.toString(): 2014-05-14T18:30:00Z
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.
I am Having Date with it's timezone, I want to convert it to another Timezone, E.g. I have Date '3/15/2013 3:01:53 PM' which is in TimeZone 'GMT-06:00'. I want to convert this in 'GMT-05:00' timezone. I have search lot, and I am confuse about How actually Date is working. How to Apply timezone to date. I have try with SimpleDateFormat, Calender and also with offset.
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss aaa XXX");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
Date dt = null;
try {
dt = df.parse("3/15/2013 3:01:53 PM -06:00");
} catch (ParseException e) {
e.printStackTrace();
}
String newDateString = df.format(dt);
System.out.println(newDateString);
It returns output
03/15/2013 09:01:53 AM Z.
I guess it should be
03/15/2013 09:01:53 PM Z, because time in 'GMT-06:00' timezone, so it should be HH+6 to get time in GMT. I want Date in "yyyy-MM-dd HH:mm:ss" format where HH is in 24 hour.Please Help me with example. Thanks in advance.
EDIT :
I am converting the string into date using SimpleDateFormat
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss aaa");
Date dt = null;
try {
dt = df.parse("3/15/2013 3:01:53 PM");
} catch (ParseException e) {
e.printStackTrace();
}
Now, as you say, I specify to Calendar that my date is in 'GMT-06:00' timezone and set my date,
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-6"));
cal.setTime(dt);
Now, I am telling calendar that I want date in 'GMT'
cal.setTimeZone (TimeZone.getTimeZone("GMT"));
System.out.println(cal.getTime());
OutPut:
Fri Mar 15 03:01:53 CDT 2013
Please know me if i am going wrong.
You need TWO format objects, one for parsing and another one for printing because you use two different timezones, see here:
// h instead of H because of AM/PM-format
DateFormat parseFormat = new SimpleDateFormat("M/dd/yyyy hh:mm:ss aaa XXX");
Date dt = null;
try {
dt = parseFormat.parse("3/15/2013 3:01:53 PM -06:00");
}catch (ParseException e) {
e.printStackTrace();
}
DateFormat printFormat = new SimpleDateFormat("M/dd/yyyy hh:mm:ss aaa XXX");
printFormat.setTimeZone(TimeZone.getTimeZone("GMT-05"));
String newDateString = printFormat.format(dt);
System.out.println(newDateString);
Output: 3/15/2013 04:01:53 PM -05:00
If you want HH:mm:ss (24-hour-format) then you just replace
hh:mm:ss aaa
by
HH:mm:ss
in printFormat-pattern.
Comment on other aspects of question:
A java.util.Date has no internal timezone and always refers to UTC by spec. You cannot change it inside this object. A timezone conversion is possible for the formatted string, however as demonstrated in my code example (you wanted to convert to zone GMT-05).
The question then switches to the new requirement to print the Date-object in ISO-format using UTC timezone (symbol Z). This can be done in formatting by replacing the pattern with "yyyy-MM-dd'T'HH:mm:ssXXX" and explicitly setting the timezone of printFormat to GMT+00. You should clarify what you really want as formatted output.
About java.util.GregorianCalendar: Setting the timezone here is changing the calendar-object in a programmatical way, so it affects method calls like calendar.get(Calendar.HOUR_OF_DAY). This has nothing to do with formatting however!
tl;dr
OffsetDateTime.parse(
"3/15/2013 3:01:53 PM -06:00" ,
DateTimeFormatter.ofPattern( "M/d/yyyy H:mm:ss a XXX" )
).withOffsetSameInstant(
ZoneOffset.of( -5 , 0 )
)
2013-03-15T15:01:53-06:00
java.time
The Answer by Hochschild is correct but uses outdated classes. The troublesome old date-time classes bundled with the earliest versions of Java have been supplanted by the modern java.time classes.
Parse your input string as a OffsetDateTime as it contains an offset-from-UTC but not a time zone.
String input = "3/15/2013 3:01:53 PM -06:00";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d/yyyy h:mm:ss a XXX" );
OffsetDateTime odt = OffsetDateTime.parse( input , f );
odt.toString(): 2013-03-15T15:01:53-06:00
Tip: Save yourself some hassle and use the ISO 8601 formats when exchanging date-time data as text. The java.time classes use these standard formats by default when parsing/generating strings.
Apparently you want to see the same moment as viewed by the people elsewhere using a different offset-from-UTC.
ZoneOffset offset = ZoneOffset.of( -5 , 0 ) ;
OffsetDateTime odt2 = odt.withOffsetSameInstant( offset ) ;
We see the offset changes from 6 to 5, and the hour-of-day changes accordingly from 15 to 16. Same simultaneous moment, different wall-clock time.
odt2.toString(): 2013-03-15T16:01:53-05:00
Generating strings
I want Date in "yyyy-MM-dd HH:mm:ss" format where HH is in 24 hour.
I suggest you always include some indication of the offset or zoneunless your are absolutely certain the user understands from the greater context.
Your format is nearly in standard ISO 8601 format. You could define your own formatting pattern, but I would just do string manipulation to replace the T in the middle with a SPACE.
String output = odt2.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).replace( "T" , " " ) ;
2013-03-15 16:01:53
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.
I want to ask, how can I put Date from Parse.com (which is in format "Sat Mar 01 15:52:20 GMT+1:00 2014") to same Date type as the date and time in system. Second thing I want to ask is, how to get only for example "month:day:hour:minute:year" from Parse.com even though the Date is given in format as written above.
Thanks for any suggestion!
You just try like this you can achieve the Date format conversion easily...
String inputPattern = "yyyy-MM-dd hh:mm:ss";
String outputPattern = "dd-MMM-yyyy hh:mm a";
SimpleDateFormat inFormat = new SimpleDateFormat(inputPattern);
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
Date date1 = null;
if (date != null) {
try {
date1 = inFormat.parse(date);
str = outputFormat.format(date1);
Log.d(null, str);
} catch (ParseException e) {
e.printStackTrace();
}
} else {
str = " ";
}
tl;dr
OffsetDateTime.parse( // Parse input string as a `OffsetDateTime` object, with the given offset-from-UTC.
"Sat Mar 01 15:52:20 GMT+1:00 2014" ,
DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss O uuuu" , Locale.US )
).toInstant() // Convert from the given offset-from-UTC to UTC.
Details
You may be confused about how date and time tracking work in Java. The java.util.Date class tracks the number of milliseconds since the Unix epoch. It has no String inside.
java.time
The modern approach uses the java.time classes.
If you are receiving a string such as "Sat Mar 01 15:52:20 GMT+1:00 2014", parse as a OffsetDateTime. By the way, this is a terrible format. Better to exchange date-time values as text using standard ISO 8601 formats, whenever possible.
Specify a formatting pattern to match your input.
Note the Locale argument. Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
String input = "Sat Mar 01 15:52:20 GMT+1:00 2014" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss O uuuu" , Locale.US );
OffsetDateTime odt = OffsetDateTime.parse( input , f );
Generate a String to represent the value of this OffsetDateTime object in standard ISO 8601 format.
odt.toString(): 2014-03-01T15:52:20+01:00
To generate strings in other formats, search Stack Overflow for DateTimeFormatter.
To view that same moment through the wall-clock time of UTC, extract a Instant object.
Instant instant = odt.toInstant() ; // Extract an `Instant`, always in UTC.
Joda-Time
UPDATE: This section is now outmoded, but retained as history. FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
Joda-Time is the go-to library for data-time handling. The java.util.Date & .Calendar & SimpleTextFormat classes bundled with Java are notoriously troublesome (not Sun’s best work). Those old classes have been supplanted in Java 8 by the new java.time package which is inspired by Joda-Time.
In Joda-Time, a DateTime object is similar to a java.util.Date object in that it tracks number of milliseconds-since-Unix-epoch. But different in that a DateTime does know its own assigned time zone.
Here's a bit of code to get you started. Search StackOverflow to find more examples.
One problem with that string you gave as example. The offset-from-GMT is +1:00 without a leading zero before the 1. That cannot be parsed directly by Joda-Time. Hopefully that was a typo made by you and not a lousy format being generated by Parse.com.
The formats you see below are the standard, ISO 8601.
String input = "Sat Mar 01 15:52:20 GMT+01:00 2014";
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "EEE MMM dd HH:mm:ss 'GMT'Z yyyy" ).withLocale( Locale.ENGLISH );
DateTimeZone timeZone = DateTimeZone.forID( "America/Los_Angeles" );
DateTime dateTimeLosAngeles = formatterInput.withZone( timeZone ).parseDateTime( input );
DateTime dateTimeUtc = dateTimeLosAngeles.withZone( DateTimeZone.UTC );
DateTimeFormatter formatterOutput = DateTimeFormat.forStyle( "SS" );
String output = formatterOutput.print( dateTimeLosAngeles );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTimeLosAngeles: " + dateTimeLosAngeles );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "output: " + output );
When run…
input: Sat Mar 01 15:52:20 GMT+01:00 2014
dateTimeLosAngeles: 2014-03-01T06:52:20.000-08:00
dateTimeUtc: 2014-03-01T14:52:20.000Z
output: 3/1/14 6:52 AM
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….