I'm getting an unparseable date exception using:
"2021-07-20T12:35:20-07:00".toDate()!!
#SuppressLint("SimpleDateFormat")
fun String.toDate() : Date? {
return SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(this)
}
From the SimpleDateFormat docs
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
The Z directive expects the time zone to be specified without a colon, whereas X allows a colon. Either format your dates like
2021-07-20T12:35:20-0700
or use the ISO 8601 timezone designator, rather than the RFC 822 one
yyyy-MM-dd'T'HH:mm:ssX
Try it online!
java.time through desugaring
I recommend that you uses java.time, the modern Java date and time API, for your date and time work. Excuse my Java syntax:
public static OffsetDateTime toDate(String s) {
return OffsetDateTime.parse(s);
}
Let’s try it:
OffsetDateTime dateTime = toDate("2021-07-20T12:35:20-07:00");
System.out.println(dateTime);
Output is:
2021-07-20T12:35:20-07:00
We do not need to specify any formatter at all. Your string is in ISO 8601 format. OffsetDateTime and the other classes of java.time parse the most common variants of ISO 8601 as their default, that is, without any explicit formatter. Which is good because as you experienced, constructing a formatter is error-prone.
In case you need a Date object for an old API not yet upgraded to Java time, the conversion is:
Date oldfashionedDate = Date.from(dateTime.toInstant());
System.out.println(oldfashionedDate);
Output (from a device in Europe/Brussels time zone):
Tue Jul 20 21:35:20 CEST 2021
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.
Wikipedia article: ISO 8601
Related
Is there any way to get the current date in Scala without using Java class import java.text.SimpleDateFormat and import java.util.Date?
java.time
You should not be importing java.text.SimpleDateFormat or java.util.Date. Those troublesome old classes are now legacy, supplanted by the java.time classes.
While I do not know Scala syntax, here is Java syntax.
java.time.Instant.now() // Current moment in UTC, with a resolution of nanoseconds.
…and…
java.time.ZonedDateTime.now( ZoneId.of( "Africa/Tunis" ) ) // Current moment adjusted to the wall-clock time as used by the people in a particular region (time zone).
…and…
java.time.LocalDate.now( ZoneId.of( "Pacific/Auckland" ) ) // Current date (date-only, no time-of-day nor zone) of the people in a particular region (time zone).
http://pavkin.ru/cross-platform-polymorphic-datetime-values-in-scala-with-type-classes/
The Goal
There’s no solution without a goal. Precise goal will also provide correct context for reasonings in this article. So let me state it.
My primary goal is to be able to write cross-platform code that operates on date/time values with full time zone support.
This also means that I will need implementation(s) that behave consistently across JVM and browser. We’re Scala programmers, so let’s choose JVM behaviour semantics as our second goal.
Options explored in the article are
https://github.com/scala-js/scala-js-java-time
This library is the future of cross-platform date/time code. It’s effectively Java 8 time, written from scratch for ScalaJS.
At the time of writing this post, scala-js-java-time already provides LocalTime, LocalDate, Duration , and a handful of other really useful java.time.* classes (full list here).
https://github.com/soc/scala-java-time
Scala Java-Time is a fork of ThreeTen backport project. So it’s main purpose is to provide java.time.* -like functionality on Java 6 & 7.
It is also compiled to ScalaJS, which means we can write cross-platform code with it. And we can even use (to some extent) LocalDateTime!
https://github.com/mdedetrich/soda-time
Soda time is a port of Joda to ScalaJS.
It’s in early development stages and also doesn’t have time zones in ScalaJS, but I still added it to the list, because developers took an interesting approach: they are converting original Joda code with ScalaGen.
The author then goes to recommend that at the time of writing the article, (Published 11.11.2016)
There’s no cross-platform library with full time zone support. And for JavaScript runtime there’s only MomentJS, that really fits our requirements.
So unless one of those have evolved, or you only need a subset of datetime functions, or another solution has raised it's head, you are probably stuck implementing some sort of interface over the behavior needed, and swapping it out based on whether you are on java or scalajs.
Well, it's unclear - beside the hint about newer classes mentioned by Basil - why you would do this, need this.
On unix-like systems you can use the System date, probably on Windows systems too, but with the same syntax? You probably loose system independency:
scala> import sys.process._
import sys.process._
scala> "date".!
Mi 31. Jan 07:09:04 CET 2018
res150: Int = 0
If you have a database, these often provide the date/time too.
Then you could try to get the date via TCP/IP.
All this solutions are in allmost all cases inferior to using the newer Java classes and even the older ones.
I am trying to implement Runtime Locales in GWT, But I could not able to get it working. There is very limited documentation available on net. So could you please help me in implementing Runtime Locales in GWT. It will be helpful if someone give an example on how to implement Runtime Locales, because I have already spent lot of time on implementing Runtime Locales. So if somebody explain how to implement it using an example that would be great.
The reason I need Runtime Locale is, I want to get date format, month names and weekdays names based on locale string (Ex : en_US, es_MX etc), I mean I want to obtain Locale object from locale string as it is possible in Java. As of my knowledge we cannot get information about any other locale than the default locale that GWT has loaded. and i don't want to use Compile time Locales because of the compile time overhead and increase on static footprint.
This is the documentation for implementing Locale in GWT which I am referring - http://www.gwtproject.org/doc/latest/DevGuideI18nLocale.html
Thanks,
Madhusudhan.
I think you miss one important thing about runtime locales:
[...] all locales that GWT knows about that inherit from your compile-time locale will be automatically included [...]
As an example, you might have one set of translations for all of Spanish as spoken in Latin America (es_419), yet allow users to choose a country-specific locale such as Argentinian Spanish (es_AR).
Note that DateTimeFormatInfoImpl_es_AR extends DateTimeFormatInfoImpl_es_419.
But there is a trick that allow you to get date format in any locale by getting DateTimeFormatInfo implementation directly for given locale:
DateTimeFormatInfo format = new DateTimeFormatInfoImpl_es_MX();
format.dateFormatLong(); // d 'de' MMMM 'de' y
Date has many deprecated methods, i.e, getTime, getMounth, etc. Should I avoid using it?
Also, what is the difference between: Date, Calendarand DataPicker?
Date was deprecated in the JDK v1.1; in other words relatively early during the (ongoing) development of the environment. It was deprecated because of incompatibility with international time standards; while it was intended to reflect coordinated universal time (UTC) it was found that on machines that use the GMT time standard or those that do not reflect a "leap second" (an extra second once every year or two) that the Date class might not be exactly accurate.
For this reason, it is recommended that you use Calendar.get(...) instead of Date's respective methods! Also, Java8 has a UI component, DatePicker, which use's the new LocalDate class (which is a localized replacement for the deprecated Date class).
Date date = new Date();
int lastMonth = date.getMonth();
int lastYear = 1900 + date.getYear();
I have this code in my GWT project but a lot of method of java.util.Date is deprecated, 22/33 methods.
So I want to use Calendar/GregorianCalendar : it does not work. It said there is a missing package.
What is the best practice to replace these line of code with a not deprecated code ?
Don't.
java.util.Calendar is almost impossible to emulate, and has a way too high overhead. java.util.Date, while far from ideal, is the closest to JavaScript's Date, so it's the one you should use in GWT world.
JSR 310 is promising (don't know how well it could be emulated though, and with how much overhead compared to java.util.Date) but isn't there yet.
There's also Joda Time (from the same author as JSR 310, JSR 310 aims at bringing Joda Time to the JDK along with fixing some of its early design mistakes), but most GWT ports have long been abandonned.
In the end: use java.util.Date.
And if you find the deprecation warnings annoying, then suppress them: #SuppressWarnings("deprecated").
java.util.Date is not deprecated! Admittedly many methods of it are (like getMonth and getYear) which I try to avoid using. In the case of GWT you can use something like DateTimeFormat to do date formatting and parsing.
I have a date string (well, NSData, but that's easy to convert to a string) that's in what I believe is the format the HTTP standard uses:
Mon Apr 17 19:34:46 UTC 2006
Is there any better (i.e. less error-prone) way to parse that than specifying the format string by hand in an NSDateFormatter?
(My application is an iPhone app, but I suspect standard Cocoa solutions will work too, since NSDate and NSDateFormatter are part of Foundation.)
No, I don't think there is a better way.
If you have some outside input, you must know the format of your input beforehand, and you can only prepare for problems, i.e. a fail over parser with an alternate NSDateFormatter.