0

I want to create an instance of Calendar with string date coming from server. Now I don't know what format server is sending .

It can be changed for different countries. I know I can ask them to add another key for dateFormat and create Calendar from it. But still I want to know Is there any way to create Calendar Instance without knowing current string date format.

I have gone through this and this. But none fulfill my requirement

Community
  • 1
  • 1
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
  • You have to know something. You can use a Locale specific Date parser; I'd recommend sticking to the new datetime package in JDK 8. – duffymo Nov 23 '16 at 13:40
  • you can request the server guy to provide date/time in [Timestamp](https://docs.oracle.com/javase/7/docs/api/java/sql/Timestamp.html) format so you can format it in your side – SaravInfern Nov 23 '16 at 13:46
  • http://stackoverflow.com/questions/454315/how-do-you-format-date-and-time-in-android This might help you – Adeel Shahzad Nov 23 '16 at 13:47

2 Answers2

3

This is impossible.

If the server sends the value "1/2/2017", you have no way of knowing if this refers to January 2nd or February 1st.

If the server sends the value "מָחָר", in theory you could realize that this might be a Hebrew translation of the word "tomorrow" (at least, according to Google Translate), but even then, it is not clear whether this is to be taken relative to today or some other date.

If the server sends the value "I want to create an instance of Calendar with string date coming from server", you have no means of creating a date from that, at least using any algorithm that would make sense to people.

And so on.

The only reason a server should return a date in an arbitrary format is if the date would only ever be read by the user who provided the value in the first place and presented as plain text verbatim, without parsing. Otherwise, the server should supply the date in a standardized format, with the UI consuming that date being responsible for formatting it in a user-friendly (and, ideally, locale-aware) fashion.

You're welcome to try to brute-force the problem, iterating over a series of date formats and seeing if any result in a seemingly-valid date. This fails the 1/2/2017 scenario (as there are at least two formats that would return a seemingly-valid date), but perhaps you know enough about the server to narrow down the possible formats to reduce the odds of collisions like this.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

The Joda Date & Time API has a date parser which can parse date strings in many formats. Note that some datetime strings can be ambiguous: 10-09-2003 could mean October 9 or September 10.

Community
  • 1
  • 1
Ano
  • 96
  • 7