I am having this string "Mon Nov 11 10:36:53 GMT+02:00 2019". What is the pattern when using SimpleDateFormat();? Is there some way I can test or generate it without multiple try and error?
java.time and ThreeTenABP
What is the pattern when using SimpleDateFormat();?
My suggestion is that you don’t use SimpleDateFormat. That class is notoriously troublesome and long outdated. On Android — and on your API level too — you can use java.time, the modern Java date and time API.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
String stringWereHaving = "Mon Nov 11 10:36:53 GMT+02:00 2019";
ZonedDateTime dateTime = ZonedDateTime.parse(stringWereHaving, formatter);
System.out.println(dateTime);
Output is:
2019-11-11T10:36:53+02:00[Etc/GMT-2]
The only confusing thing here is that the sign used in the time zone name Etc/GMT-2 has been intentionally reversed compared to normal usage.
Only if you need an old-fashioned Date object for a legacy API not yet upgraded to java.time, convert like this:
Instant i = dateTime.toInstant();
Date oldfashionedDate = DateTimeUtils.toDate(i);
System.out.println(oldfashionedDate);
Mon Nov 11 09:36:53 CET 2019
Output comes from my computer in Europe/Copenhagen time zone, so the hour of day is adjusted by 1 hour compared to your input at offset `02:00. We have got the same point in time as in the string.
Is there some way I can test or generate it without multiple try and
error?
There’s always Java SimpleDateFormat Online Tester. I give you the link at the bottom. I don’t know of a similar service for DateTimeFormatter. Many of the patterns are the same, also the one I am using above, so it’s probably worthwhile trying.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Java SimpleDateFormat Online Tester
Try using
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Test{
public static void main(String[] args) {
//Try This
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM dd hh:mm:ss 'GMT' Z yyyy");
System.out.println(simpleDateFormat.format(new Date()));
}
}
What do you mean " Is there some way I can test or generate it without multiple try and error?"
BTW, I'm using DateFormat dateFormat = new SimpleDateFormat(<put your desired pattern here via STRING>);
and get the current date:
Date date = new Date();
String result = dateFormat.format(date); // formatting the date and passing it on string.
sample code:
DateFormat dateFormat = new SimpleDateFormat("MMM. dd, yyyy EEE HH:mm:ss");
Date date = new Date();
result = dateFormat.format(date);
Output : Nov. 13, 2019 Wed 17:02:00
Related
I am trying to parse various slightly different date strings for an Android application.
Two examples are:
Thu, 20 Aug 2020 13:30:16 +0000
Wed, 19 Aug 2020 15:28:47 GMT
Here is how I tried parsing these Strings:
Date pubDate = org.apache.commons.lang3.time.DateUtils.parseDate(dateString,
"EEE, dd MMM yyyy HH:mm:ss Z", "EEE, dd MMM yyyy HH:mm:ss zzz");
As far as I can tell this should work, but I am getting java.text.ParseException: Unable to parse the date: Wed, 19 Aug 2020 15:28:47 GMT exceptions for both those examples. What am I doing wrong here?
Your format is built into java.time
Use DateTimeFormatter.RFC_1123_DATE_TIME; it works for both of your strings. It’s really the same format, only with the offset from UTC (or GMT) denoted differently. DateTimeFormatter is part of java.time, the modern Java date and time API. I recommend that you prefer java.time over Date and DateUtils, also because the Date class is poorly designed and long outdated.
String s = "Thu, 20 Aug 2020 13:30:16 +0000";
OffsetDateTime dt = OffsetDateTime.parse(s, DateTimeFormatter.RFC_1123_DATE_TIME);
System.out.println(dt);
Output is:
2020-08-20T13:30:16Z
Let’s try with your other string example:
String s = "Wed, 19 Aug 2020 15:28:47 GMT";
2020-08-19T15:28:47Z
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
Java 8+ APIs available through desugaring
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Your time zones are in 2 different formats:
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
The first one looks like it follows the format:
EEE, dd MMM yyyy HH:mm:ss Z", "EEE, dd MMM yyyy HH:mm:ss Z
While the second is of the format:
EEE, dd MMM yyyy HH:mm:ss Z", "EEE, dd MMM yyyy HH:mm:ss z
I do not see any problem with your formats.
Demo:
import java.text.ParseException;
import java.util.Date;
public class Main {
public static void main(String[] args) throws ParseException {
String[] dateStrings = { "Wed, 19 Aug 2020 15:28:47 GMT", "Thu, 20 Aug 2020 13:30:16 +0000" };
for (String dateString : dateStrings) {
Date pubDate = org.apache.commons.lang3.time.DateUtils.parseDate(dateString, "EEE, dd MMM yyyy HH:mm:ss Z",
"EEE, dd MMM yyyy HH:mm:ss zzz");
System.out.println(pubDate);
}
}
}
Output:
Wed Aug 19 16:28:47 BST 2020
Thu Aug 20 14:30:16 BST 2020
However, I strongly suggest you stop using the outdated and error-prone java.util date-time API and SimpleDateFormat. Switch to the modern java.time date-time API and the corresponding formatting API (java.time.format). Learn more about the modern date-time API from Trail: Date Time.
Using modern date-time API:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test strings
String[] dateStrings = { "Wed, 19 Aug 2020 15:28:47 GMT", "Thu, 20 Aug 2020 13:30:16 +0000" };
// Define formatter
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("[EEE, dd MMM yyyy HH:mm:ss Z][EEE, dd MMM yyyy HH:mm:ss zzz]", Locale.ENGLISH);
for (String dateString : dateStrings) {
ZonedDateTime zdt = ZonedDateTime.parse(dateString, formatter);
System.out.println(zdt);
}
}
}
Output:
2020-08-19T15:28:47Z[GMT]
2020-08-20T13:30:16Z
If your android version is not compliant with Java-8, you can backport using ThreeTen-BackportCheck. Check How to use ThreeTenABP in Android Project
I am getting a string from service, 2 Nov 2019 07:30 pm, the date is in United States Central Time.
Now i need to know how much time is remaining between current time and this date.
I am using following code, but this is not giving accurate difference.
SimpleDateFormat ticketDateFormat = new SimpleDateFormat("MMM d yyyy hh:mm a");
Date parsedDate= null;
try {
parsedDate= ticketDateFormat.parse(dateTimeString);
DateFormat formatter = new SimpleDateFormat("MMM d yyyy hh:mm a");
TimeZone timeZone = TimeZone.getTimeZone("CST");
formatter.setTimeZone(timeZone);
parsedDate= ticketDateFormat.parse(formatter.format(parsedDate));
long totalTimeRemainingInMillis= Math.abs(currentDateTime.getTime()- (parsedDate.getTime()));
long diffInHours = TimeUnit.MILLISECONDS.toHours(totalTimeRemainingInMillis);
} catch (ParseException e) {
e.printStackTrace();
}
Although it is not clear in your question where you are getting current time from, my guess is that the problem is in the way you are using TimeZone. You are setting the TimeZone in the formatter then parsing the date which you say is already in CST.
Here is an alternate way you can do the same thing and then compare your results:
LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("LLL d yyyy hh:mm a");
LocalDateTime parse = LocalDateTime.parse("Nov 2 2019 07:30 PM", fmt);
System.out.println(Duration.between(dateTime, parse).toHours());
String date "2 Nov 2019 07:30 pm" should be parsed this way:
new SimpleDateFormat("dd MMM yyyy hh:mm a")
Not this way:
new SimpleDateFormat("MMM d yyyy hh:mm a");
Use following code for result
SimpleDateFormat dateFormat = new SimpleDateFormat("d MMM yyyy hh:mm a");
TimeZone timeZone = TimeZone.getTimeZone("CST");
dateFormat.setTimeZone(timeZone);
Date event_date = dateFormat.parse("2 Nov 2019 07:30 pm");
Date current_date = new Date();
long diff = event_date.getTime() - current_date.getTime();
long Days = diff / (24 * 60 * 60 * 1000);
long Hours = diff / (60 * 60 * 1000) % 24;
long Minutes = diff / (60 * 1000) % 60;
long Seconds = diff / 1000 % 60;
Log.i(TAG, Hours + "," + Minutes + "," + Seconds);
java.time and ThreeTenABP
This will work on your Android API level:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("d MMM uuuu hh:mm ")
.parseCaseInsensitive()
.appendPattern("a")
.toFormatter(Locale.US);
ZoneId zone = ZoneId.of("America/Chicago");
ZonedDateTime currentDateTime = ZonedDateTime.now(zone);
String dateTimeString = "2 Nov 2019 07:30 pm";
ZonedDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter)
.atZone(zone);
long diffInHours = ChronoUnit.HOURS.between(currentDateTime, dateTime);
System.out.println("Difference in hours: " + diffInHours);
When I ran this snippet just now, the output was:
Difference in hours: 541
I am using java.time, the modern Java date and time API. It’s much nicer to work with than the old and poorly designed Date and SimpleDateFormat. On one hand parsing lowercase am and pm requires a little more code lines (since they are normally in uppercase in US locale), on the other hand java.time validates more strictly, which is always good. Advantages we get for free include: We need no time zone conversions, we can do everything in Central Time. The calculation of the difference in hours is built in, just requires one method call.
Specify locale for your formatter, or it will break when some day your code runs on a JVM with a non-English default locale. Specify US Central Time as America/Chicago. Always use this region/city format for time zones. CST is deprecated and also lying since it gives you CDT at this time of year.
Question: Doesn’t java.time require Android API level 26 or higher?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Now I have two different formats of date written in string:
String date1 = "2018-10-12 18:01:01";// yyyy-MM-dd HH:mm:ss
String date2 = "2018-10-12 18:01";//yyyy-MM-dd HH:mm
I am using joda and I want to convert the string to DateTime,the basic way is to use two formatter to parse each of them:
DateTimeFormatter formatter1 = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTimeFormatter formatter2 = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
DateTime dt1 = formatter1.parseDateTime(date1);
DateTime dt2 = formatter2.parseDateTime(date2);
Above code blocks works fine but it created two formatter,since the date formate is very similar(the latter one just lack of seconds),I am wonder if there is a way that I can just use one formatter to parse all of them or I have to use two formatter?
Note:
due to the production enviroment limit,I can not use java8 now,so I want to the answer based on joda
Thanks in advance!
I just tried as below,and got IllegalArgumentException: Invalid format
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dt1 = formatter.parseDateTime(date1);
DateTime dt2 = formatter.parseDateTime(date2);
You can indicate that some parts of the format are optional using []
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm[:ss]");
LocalDateTime dateTime = LocalDateTime.parse("2018-10-12 18:01:01", formatter);
LocalDateTime dateTime1 = LocalDateTime.parse("2018-10-12 18:01", formatter);
System.out.println(dateTime + " " + dateTime1);
result is
2018-10-12T18:01:01 2018-10-12T18:01
Please see Patterns for Formatting and Parsing section for more info.
Two options:
Use java.time, the modern Java date and time API through the ThreeTen Backport library.
Use Joda-Time as you are already doing.
ThreeTen Backport
Two quotes from the Joda-Time home page:
Users are now asked to migrate to java.time (JSR-310).
Note that Joda-Time is considered to be a largely “finished” project.
No major enhancements are planned. If using Java SE 8, please migrate
to java.time (JSR-310).
The good news is you can migrate even if using Java 6 or 7. The developers of java.time (lead by Stephen Colebourne, also the lead developer of Joda-Time) have also developed the ThreeTen Backport, the backport of java.time for Java 6 and 7. See the link at the bottom.
Anton Balaniuc is already showing the code in his good answer, so there’s no use for me to repeat that here.
Joda-Time
String date1 = "2018-10-12 18:01:01";// yyyy-MM-dd HH:mm:ss
String date2 = "2018-10-12 18:01";//yyyy-MM-dd HH:mm
DateTimeFormatter parser = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd HH:mm")
.appendOptional(DateTimeFormat.forPattern(":ss").getParser())
.toFormatter();
DateTime dt1 = parser.parseDateTime(date1);
DateTime dt2 = parser.parseDateTime(date2);
System.out.println("dt1: " + dt1);
System.out.println("dt2: " + dt2);
On my computer in Europe/Copenhagen time zone the output from this snippet was:
dt1: 2018-10-12T18:01:01.000+02:00
dt2: 2018-10-12T18:01:00.000+02:00
As you can see, the key to specifying optional parts in the format is the appendOptional method of DateTimeFormatterBuilder.
Links
Joda-Time home page
Answer by Anton Balaniuc showing the code for java.time
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
You can use DateTimeFormatterBuilder class, something like this.
private DateTimeFormatter formatterBuilder() {
return new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd HH:mm")
.optionalStart().appendPattern(":ss").optionalEnd()
.toFormatter();
}
There's a lot of questions on here on SimpleDateFormat but I can't seem to find anything on this issue. I'm running into issues with different output from the exact same code running on Android vs the JDK. I'm running in Eclipse and using the emulator to test Android. JDK version 1.7 and Android 4.4.
Any ideas on how to make Android output dates in the JDK style format?
TimeZone GMT_ZONE = TimeZone.getTimeZone("GMT");
String RFC1123_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z";
final DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN, LOCALE_US);
rfc1123Format.setTimeZone(GMT_ZONE);
String dateString = rfc1123Format.format(new Date());
JDK 1.7 dateString value: Fri, 20 Dec 2013 00:46:21 GMT
Android 4.4 dateString value: Fri, 20 Dec 2013 00:46:21 GMT+00:00
Android != Java
Android libraries are an imitation of the Java libraries but not exact copies. Thus the lawsuit between Oracle and Google. So you may see variations in behavior.
Joda-Time
If you want a consistent, and superior, experience when doing work with date-times, use the third-party open-source Joda-Time library. Joda-Time is meant to supplant the notoriously bad java.util.Date/Calendar classes.
JSR 310
Another option might be the Java 7 backport of JSR 310: Date and Time API java.time.* classes bundled with Java 8.
RFC 1123 Format
Regarding the follow-up question you added as a comment:
Any idea what pattern would produce the Fri, 20 Dec 2013 00:46:21 GMT format output on Android?
Surprisingly, Joda-Time 2.3 seems to lack a built-in formatter for that old RFC 1123 format. But the following home-brew format seems to do the job, provided you remember to convert the DateTime to UTC, as shown below.
// © 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 nowInParis = new DateTime( DateTimeZone.forID( "Europe/Paris" ) );
DateTimeFormatter formatter = DateTimeFormat.forPattern("E, d MMM yyyy HH:mm:ss 'GMT'").withLocale( Locale.US );
String nowInParisAsStringGMT = formatter.print( nowInParis.toDateTime( DateTimeZone.UTC ) );
Dump to console…
System.out.println( "nowInParisAsStringGMT: " + nowInParisAsStringGMT );
System.out.println( "nowInParis: " + nowInParis );
When run…
nowInParisAsStringGMT: Fri, 20 Dec 2013 05:03:58 GMT
nowInParis: 2013-12-20T05:03:58.175+01:00
Here is a slightly modified version of Basil's answer for those who don't want to use Joda-Time:
private String toRfc1123(Date date) {
SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
return formatter.format(date);
}
I am new to Java, usually work with PHP.
I am trying to convert this string:
Mon Mar 14 16:02:37 GMT 2011
Into a Calendar Object so that I can easily pull the Year and Month like this:
String yearAndMonth = cal.get(Calendar.YEAR)+cal.get(Calendar.MONTH);
Would it be a bad idea to parse it manually? Using a substring method?
Any advice would help thanks!
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
cal.setTime(sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done
note: set Locale according to your environment/requirement
See Also
Javadoc
tl;dr
The modern approach uses the java.time classes.
YearMonth.from(
ZonedDateTime.parse(
"Mon Mar 14 16:02:37 GMT 2011" ,
DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" )
)
).toString()
2011-03
Avoid legacy date-time classes
The modern way is with java.time classes. The old date-time classes such as Calendar have proven to be poorly-designed, confusing, and troublesome.
Define a custom formatter to match your string input.
String input = "Mon Mar 14 16:02:37 GMT 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" );
Parse as a ZonedDateTime.
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
You are interested in the year and month. The java.time classes include YearMonth class for that purpose.
YearMonth ym = YearMonth.from( zdt );
You can interrogate for the year and month numbers if needed.
int year = ym.getYear();
int month = ym.getMonthValue();
But the toString method generates a string in standard ISO 8601 format.
String output = ym.toString();
Put this all together.
String input = "Mon Mar 14 16:02:37 GMT 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
YearMonth ym = YearMonth.from( zdt );
int year = ym.getYear();
int month = ym.getMonthValue();
Dump to console.
System.out.println( "input: " + input );
System.out.println( "zdt: " + zdt );
System.out.println( "ym: " + ym );
input: Mon Mar 14 16:02:37 GMT 2011
zdt: 2011-03-14T16:02:37Z[GMT]
ym: 2011-03
Live code
See this code running in IdeOne.com.
Conversion
If you must have a Calendar object, you can convert to a GregorianCalendar using new methods added to the old classes.
GregorianCalendar gc = GregorianCalendar.from( zdt );
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
Well, I think it would be a bad idea to replicate the code which is already present in classes like SimpleDateFormat.
On the other hand, personally I'd suggest avoiding Calendar and Date entirely if you can, and using Joda Time instead, as a far better designed date and time API. For example, you need to be aware that SimpleDateFormat is not thread-safe, so you either need thread-locals, synchronization, or a new instance each time you use it. Joda parsers and formatters are thread-safe.
No new Calendar needs to be created, SimpleDateFormat already uses a Calendar underneath.
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.EN_US);
Date date = sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done
Calendar cal = sdf.getCalendar();
(I can't comment yet, that's why I created a new answer)
SimpleDateFormat is great, just note that HH is different from hh when working with hours. HH will return 24 hour based hours and hh will return 12 hour based hours.
For example, the following will return 12 hour time:
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
While this will return 24 hour time:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Parse a time with timezone, Z in pattern is for time zone
String aTime = "2017-10-25T11:39:00+09:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());
try {
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(aTime));
Log.i(TAG, "time = " + cal.getTimeInMillis());
} catch (ParseException e) {
e.printStackTrace();
}
Output: it will return the UTC time
1508899140000
If we don't set the time zone in pattern like yyyy-MM-dd'T'HH:mm:ss. SimpleDateFormat will use the time zone which have set in Setting
Yes it would be bad practice to parse it yourself. Take a look at SimpleDateFormat, it will turn the String into a Date and you can set the Date into a Calendar instance.
Simple method:
public Calendar stringToCalendar(String date, String pattern) throws ParseException {
String DEFAULT_LOCALE_NAME = "pt";
String DEFAULT_COUNTRY = "BR";
Locale DEFAULT_LOCALE = new Locale(DEFAULT_LOCALE_NAME, DEFAULT_COUNTRY);
SimpleDateFormat format = new SimpleDateFormat(pattern, LocaleUtils.DEFAULT_LOCALE);
Date d = format.parse(date);
Calendar c = getCalendar();
c.setTime(d);
return c;
}