I'm having an issue with joda-time formatting a date time string that Parse (parse.com) has stored in an sqlite table.
Sqlite creation string: "createdDate date time"
Storing parse date into table: "insert... parseObject.getCreatedAt()"
If i then use a SQLite browser to inspect the table, I see the date stored like this:
Sat Jun 15 15:44:52 PDT 2013
So going along with that, I wrote the following to convert it back into a DateTime object to give to parse as part of a query to get items that are newer than the last inserted in my table:
DateTimeFormatter format = DatetimeFormat.forPattern("yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'");
DateTime dt = formatter.parseDateTime(datahelper.getLastInsertDate(..));
The formatter is this way, because in Parse's databrowser, I can see dateTimes being stored like this:
2013-06-24T08:11:45.280Z
I get an ANR though, so I tried using the following formatter:
DateTimeFormatter format = DatetimeFormat.forPattern("EEE' 'MMM' 'dd' 'HH':'mm':'ss 'z'' 'YYYY");
DateTime dt = formatter.parseDateTime(datahelper.getLastInsertDate(..));
and I still get an ANR. The trace in eclipse shows the following:
Caused by: java.lang.IllegalArgumentException: invalid format: "Tue Jun 25 00:13:29 PDT 2013"
at org.joda.time.format.DateTimeFormatter.parseDateTime"
The second ANR trace shows:
Invalid format: "Tue Jun 25 00:13:29 PDT 2013" is malformed at "PDT
2013"
I've tried getting around that, as joda time does not parse "z" to PDT/PST, so I've put 'PDT' in my formatter to hopefully get it to work, but nothing seems to work.
Any ideas?
Edit 1: Using the accepted answer, I have a timezone formatting issue)
DateFormat originalFormat = new SimpleDateFormat("EEE MMM DDD HH:mm:ss z yyyy");
Date originaldate = originalFormat.parse(datahelper.getLastInsertdate);
Log.i("converted date: ", String.valueOf(originalDate);
Log.i("a real date: ", "String.valueOf(new Date(new Date().getTime)));
I get two outputs:
Fri Jan 25 15:14:11 PST 2013
Tue Jun 25 17:11:44 PDT 2013
why does the converted date show PST, and a standard Date shows PDT?
It seems to be a known problem Joda cannot parse Timezone names sadly. In the documentation before all the pattern syntaxes you will see this line:
The pattern syntax is mostly compatible with java.text.SimpleDateFormat - time zone names cannot be parsed and a few more symbols are supported. All ASCII letters are reserved as pattern letters, which are defined as follows:
You can see that in the documentation link here
Now the solution to your answer can be found in this answer by #BalusC located here
Hope this helps.
I think that with SQLite, because the date type is somewhat broken, the best thing to do is to store the long that you get from Date.getTime() or related Joda methods.
When you get the long from the database, re-construct your date object (e.g. new Date(long)), and then format that.
Above all, remember that (IMHO) the only sensible way to store a date is in reference to UTC, which is what you get with Date.getTime() and new Date(long) : milliseconds since Jan 1, 1970 UTC.
Once you retrieve your date, format it with whatever timezone is appropriate.
Related
I'm developing an application which takes data from Google TimeZone API.
Simply I have time in milliseconds of desired place on Earth.
For Example : 1504760156000 it's showing Date time In London which is
Thu Sep 07 2017 09:55:56
As I'm in TimeZone +05:00 from UTC if I manipulate 1504760156000 these milliseconds it will show me whole date time like below:
Thu Sep 07 2017 09:55:56 GMT+0500 (Pakistan Standard Time)
but I want to show:
Thu Sep 07 2017 09:55:56 GMT+0100 (British Summer Time)
The problem is: I have correct date and time for London but enable to show/change TimeZone without changing Time because Time is correct according to London.
UPDATED
After getting some comments. You are not getting me here in my example.
Suppose I am in Pakistan and Time here is 1:55 PM so I asked GOOGLE API via my application to tell me whats the time in London at moment. Google API tell me time in London is 1504760156000 (9:55 AM) in milliseconds if I convert these milliseconds to Date Object it will print out like below:
Date date =new Date(1504760156000)
Thu Sep 07 2017 09:55:56 GMT+0500 (Pakistan Standard Time)
It will manipulate it according to my Local TimeZone but I want results like below
Thu Sep 07 2017 09:55:56 GMT+0100 (British Summer Time)
Updated 2
I prepared timestamp in seconds in UTC as Google Time Zone API needed timestamp UTC in form of seconds
"https://maps.googleapis.com/maps/api/timezone/json?location="+Latitude +","+Longitude+"×tamp="+currentTimeUTCinSeonds+"&key="API KEY"
Google API respond me with below JSON against London.
{
"dstOffset" : 3600,
"rawOffset" : 0,
"status" : "OK",
"timeZoneId" : "Europe/London",
"timeZoneName" : "British Summer Time"
}
According to Docs:
Calculating the Local Time
The local time of a given location is the sum of the timestamp
parameter, and the dstOffset and rawOffset fields from the result.
I Sum up result timestamp+rawoffset+dstoffset*1000='1504760156000' (at moment when I tried it)
Code from Project
Long ultimateTime=((Long.parseLong(timeObject1.getDstOffset())*1000)+(Long.parseLong(timeObject1.getRawOffset())*1000)+timestamp*1000);
timeObject1.setTimestamp(ultimateTime); //its Sime POJO object to save current time of queried Location
Date date=new Date(ultimateTime);
date1.setText("Date Time : "+date);
As I said I'm manipulating result in Local Time Zone so it gave me below result at that time:
Thu Sep 07 2017 09:55:56 GMT+0500 (Pakistan Standard Time)
But I knew API gave me correct time. The problem is Local offset from UTC . I just want to change GMT+0500 to GMT+0100
Timestamps represent an "absolute" value of a time elapsed since epoch. Your currentTimeUTCinSeconds, for example, represent the number of seconds since unix epoch (which is 1970-01-01T00:00Z, or January 1st 1970 at midnight in UTC). Java API's usually work with the number of milliseconds since epoch.
But the concept is the same - those values are "absolute": they are the same for everyone in the world, no matter where they are. If 2 people in different parts of the world (in different timezones) get the current timestamp at the same time, they'll all get the same number.
What changes is that, in different timezones, this same number represents a different local date and time.
For example, the timestamp you're using, that corresponds to Sep 7th 2017 08:55:56 UTC, which value is 1504774556 (the number of seconds since epoch). This same number corresponds to 09:55 in London, 13:55 in Karachi, 17:55 in Tokyo and so on. Changing this number will change the local times for everyone - there's no need to manipulate it.
If you want to get a java.util.Date that represents this instant, just do:
int currentTimeUTCinSeconds = 1504774556;
// cast to long to not lose precision
Date date = new Date((long) currentTimeUTCinSeconds * 1000);
This date will keep the value 1504774556000 (the number of milliseconds since epoch). This value corresponds to 09:55 in London, 13:55 in Karachi and 17:55 in Tokyo.
But printing this date will convert it to your JVM default timezone (here is a good explanation about the behaviour of Date::toString() method). When you do "Date Time : "+date, it implicity calls toString() method, and the result is the date converted to your default timezone.
If you want the date in a specific format and in a specific timezone, you'll need a SimpleDateFormat. Just printing the date (with System.out.println or by logging it) won't work: you can't change the format of the date object itself, because a Date has no format.
I also use a java.util.Locale to specify that the month and day of week must be in English. If you don't specify a locale, it'll use the system default, and it's not guaranteed to always be English (and this can be changed, even at runtime, so it's better to always specify a locale):
// use the same format, use English for month and day of week
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z (zzzz)", Locale.ENGLISH);
// set the timezone I want
sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
// format the date
System.out.println(sdf.format(date));
The output will be:
Thu Sep 07 2017 09:55:56 GMT+0100 (British Summer Time)
Note that I don't need to manipulate the timestamp value. I don't use the google API, but I think their explanation is too confusing and the code above achieve the same results with less complication.
In your specific case, you can do:
date1.setText("Date Time : "+sdf.format(date));
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
In Android you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. To make it work, you'll also need the ThreeTenABP (more on how to use it here).
To get a date from a timestamp, I use a org.threeten.bp.Instant with a org.threeten.bp.ZoneId to convert it to a timezone, creating a org.threeten.bp.ZonedDateTime. Then I use a org.threeten.bp.format.DateTimeFormatter to format it:
int currentTimeUTCinSeconds = 1504774556;
// get the date in London from the timestamp
ZonedDateTime z = Instant.ofEpochSecond(currentTimeUTCinSeconds).atZone(ZoneId.of("Europe/London"));
// format it
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEE MMM dd yyyy HH:mm:ss 'GMT'XX (zzzz)", Locale.ENGLISH);
System.out.println(fmt.format(z));
The output is the same:
Thu Sep 07 2017 09:55:56 GMT+0100 (British Summer Time)
In your case, just do:
date1.setText("Date Time : "+fmt.format(z));
I have the following String that I would like to change to UTC:
Thu Aug 24 07:38:32 GMT+01:00 2017
I'm using Joda-Time library.
I know how to create a new Datetime eg new dateTime(DateTimeZone.UTC) but how can I create a DateTime object from the above String?
I have tried the following but get an exception. Surely there must be another way to create a DT obect without chopping the original String up? What if the external API changes how it sends my app the orignal String, my String manipulation code would fail.
DateTimeFormatter df = DateTimeFormat.forPattern("dd-MMM-YYYY HH:mm");
String strOrigTime = "Thu Aug 24 07:38:32 GMT+01:00 2017";
DateTime dt = DateTime.parse(strOrigTime, df);
Log.e(TAG, "dt after parse = " + dt.toString());
Error:
Caused by: java.lang.IllegalArgumentException: Invalid format: "Thu Aug 24 07:38:32 GMT+01:00 2017"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:866)
at org.joda.time.DateTime.parse(DateTime.java:144)
The format used (dd-MMM-YYYY HH:mm) means: day (dd) followed by -, followed by month (MMM), followed by -, followed by year (YYYY) and so on (check the javadoc for more details).
This format doesn't match the input string (which has day-of-week followed by month, followed by day, then hour/minute/second, etc). So the first thing is to use a format that matches the input, otherwise you'll always get "Invalid format" errors.
Another detail is that day of week and month names are in English, so you must also use a java.util.Locale to specify the language you're using to parse the input. If you don´t use a locale, the system default will be used, and it's not guaranteed to always be English (and it can also be changed, even at runtime, so it's always better to specify one).
I also had to add "GMT" as a literal and call withOffsetParsed() to make it include the offset (+01:00) in the parsed object:
DateTimeFormatter df = DateTimeFormat
// use a pattern that matches input
.forPattern("EEE MMM dd HH:mm:ss 'GMT'Z yyyy")
// use English locale for day of week and month
.withLocale(Locale.ENGLISH)
// include the offset (+01:00) in the parsed object
.withOffsetParsed();
String strOrigTime = "Thu Aug 24 07:38:32 GMT+01:00 2017";
DateTime dt = DateTime.parse(strOrigTime, df);
System.out.println(dt.toString());
The output is:
2017-08-24T07:38:32.000+01:00
Then, you can set the UTC timezone to this object:
dt = dt.withZone(DateTimeZone.UTC);
System.out.println(dt.toString());
The output will be:
2017-08-24T06:38:32.000Z
Note that withZone method preserves the same instant (both dates represent the same point in time), just the timezone used in the output is changed. But both dates are equivalent (they represent the same instant, as 07:38 in offset +01:00 is the same as 06:38 in UTC).
If you want all dates to be converted to UTC, you can also set this in the formatter:
// set UTC to the formatter
df = df.withZone(DateTimeZone.UTC);
Then you don't need to call withZone in the DateTime objects: all parsed dates will be converted to UTC.
You also told that "if the external API changes how it sends my app the orignal String, my String manipulation code would fail".
Well, if the input String changes, you'll have to change your format as well - there's no other way, Joda-Time can't just guess what's the format, you have to tell it.
If you want to parse more than one format, there's a way to create a formatter that uses lots of different patterns and try to parse each one, until one of them works (or throw exception if none works). You could do something like that:
// format 1
DateTimeFormatter f1 = DateTimeFormat
// use a pattern that matches input
.forPattern("EEE MMM dd HH:mm:ss 'GMT'Z yyyy")
// use English locale for day of week and month
.withLocale(Locale.ENGLISH)
// include the offset (+01:00) in the parsed object
.withOffsetParsed();
// format 2
DateTimeFormatter f2 = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss Z");
// array of all possible formats
DateTimeParser[] parsers = { f1.getParser(), f2.getParser() };
// formatter that uses all the possible formats
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
// append array of possible formats
.append(null, parsers)
// create formatter
.toFormatter().withLocale(Locale.ENGLISH).withOffsetParsed()
// set all parsed objects to UTC
.withZone(DateTimeZone.UTC);
// parse first format
System.out.println(DateTime.parse("Thu Aug 24 07:38:32 GMT+01:00 2017", formatter));
// parse second format
System.out.println(DateTime.parse("24/08/2017 07:38:32 +01:00", formatter));
Both dates will be parsed to:
2017-08-24T06:38:32.000Z
Then you can add new formats to the array, as needed.
Java new Date/Time API
Joda-Time is in maintainance mode and is being replaced by the new APIs, so I don't recommend start a new project with it. Even in joda's website it says: "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).".
If you can't (or don't want to) migrate from Joda-Time to the new API, you can ignore this section.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
The code to parse the inputs is very similar, with minor changes in the format.
And I'm using the Instant class, because you want the output in UTC, and Instant represents a UTC instant:
// format 1
DateTimeFormatter f1 = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss O yyyy", Locale.ENGLISH);
// format 2
DateTimeFormatter f2 = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss XXX");
// formatter with both formats
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
// add format 1
.appendOptional(f1)
// add format 2
.appendOptional(f2)
// create formatter
.toFormatter(Locale.ENGLISH);
// parse first format
System.out.println(Instant.from(formatter.parse("Thu Aug 24 07:38:32 GMT+01:00 2017")));
// parse second format
System.out.println(Instant.from(formatter.parse("24/08/2017 07:38:32 +01:00")));
This will output:
2017-08-24T06:38:32Z
2017-08-24T06:38:32Z
Hello I think I have a very simple question but i'm having trouble figuring it out.
I Got the Date and Time In Android using this code
String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
It gave me back this value
Apr 21, 2016 9:30:16 PM
how do I compare using to dates with that value so if I want to see if
Apr 21, 2016 9:30:16 PM
is newer or older than
Apr 21, 2016 9:35:16 PM
How would I check that Thanks
Attempt One
I Tried This
DateFormat format = new SimpleDateFormat("MM-dd-yyyy", Locale.ENGLISH);
Date fileDate = format.parse(date1);
DateFormat format2 = new SimpleDateFormat("MM-dd-yyyy", Locale.ENGLISH);
Date metaDate = format.parse(date2);
this the value for date 1 and 2 being
Apr 21, 2016 9:35:16 PM
But it threw a parse exception. I must use that value above so What do I Need to do so it doesn't break the code when it tries to parse the date
The easiest way is to use Date.before(), rather than comparing the strings. In fact its easier to convert the string back into a date than use the strings.
Hello i am new in android. Can anybody help me to find how i get date format Sun 15th July from 2012-07-15? I found examples but each of it is for various different date-formats. Please help me to find this.
try to get idea from my another answer in [Convert Date time in “April 6th, 2012 ” format][1]
[1]: Convert Date time in "April 6th, 2012 " format here you can only change the April to Sun and 2012 to month.
Like:-
DateFormatSymbols symbols = new DateFormatSymbols();
symbols.setShortWeekdays(new String[]{"Sun","Mon"....});
SimpleDateFormat format = new SimpleDateFormat("EE", symbols);
from this code you will get Days in "Sun,Mon,Tue..." Short Format
So pass this symbols in your SimpleDateFormat class.
Let's consider this code sample:
DateFormat sdf = SimpleDateFormat.getTimeInstance(SimpleDateFormat.LONG,
new Locale("ru", "RU"));
Date date = sdf.parse("8:13:05 PDT");
When I run this code on my desktop(java 1.6) all passes well, however on android devices I get exception, I think this is due to locale TimeZone:
java.text.ParseException: Unparseable date: 8:13:05 PDT
Why?
I don't believe UNIX can parse the PDT timezone. I'm having the same issue. It can handle PST & PST8PDT, but not PDT. I believe the recommended solution is to use PST8PDT instead.