I have a String this:-
Tue Oct 30 13:22:58 GMT+05:30 2012;
I want to divide time & date from SimpleDateFormate:-
DateFormat f = new SimpleDateFormat("EEE,MM/dd/yyyy hh:mm:ss);
Date d = f.parse(my string);
DateFormat date = new SimpleDateFormat("MM/dd/yyyy");
DateFormat time = new SimpleDateFormat("hh:mm:ss a");
System.out.println("Date: " + date.format(d));
System.out.println("Time: " + time.format(d));
I am getting this Error:-
java.text.ParseException: Unparseable date: "Tue Oct 30 13:22:58 GMT+05:30 2012"
Please Tell me whats the problem.
Thanks,
Deepanker
Your timestamp string does not match your pattern:
Tue Oct 30 13:22:58 GMT+05:30 2012
is no way like (not to mention syntax error in the SimpleDataFormat initialization line):
EEE,MM/dd/yyyy hh:mm:ss
So you need to make the pattern matching input data. All fields supported by SimpleDateFormat are described here.
Are you sure the date is correct??
because I tried to parse it
it gives error on GMT+05:30
just remove the :30 and it will work, see here:
String time = "Tue Oct 30 13:22:58 GMT+05 2012";
long f=Date.parse(time);
System.out.println("Time:" + f);
As it stands, your timezone offset does not match the RFC 822 standard, so I don't think you can directly parse the date without performing some cleansing on it first.
If you just want an offset, then the string should look like:
Tue Oct 30 13:22:58 +0530 2012
Note, there is no "GMT", and no colon within the offset. The corresponding pattern is then:
new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy")
Alternatively, you can specify the timezone:
Tue Oct 30 13:22:58 IST 2012
For which the pattern is:
new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy")
Related
I'm trying to convert midnight of one timezone to midnight of another time zone. Kotlin pretty much made it easy for the conversion of time zones but it does not work the same way when converting date and time to milliseconds.
Problem:
Indian Time: Mon Sep 28 00:00:00 GMT+5:30 2020
Vancouver Time: Sunday Sep 27 11:30:00 GMT-7:00 2020
What I need
Indian Time: Mon Sep 28 00:00:00 GMT+5:30 2020
Vancouver Time: Sunday Sep 27 11:30:00 GMT-7:00 2020
Here is what I tried:
val today = DateTime().withTimeAtStartOfDay().toDate() //current date and time converted to Date format
val dateOutputFormat = SimpleDateFormat("yyyy/MM/dd HH:mm:ss") // formatting the output as SimpleDateFormat
dateOutputFormat.setTimeZone(TimeZone.getTimeZone("America/Vancouver")) //Setting the timezone
Log.d("Datey2", "Before conversion ${today}") // Before conversion Mon Sep 28 00:00:00 GMT+5:30 2020
val Vancouver = Date(dateOutputFormat.format(today)).time //formatting the timezone
Log.d("Datey2", "After conversion $Vancouver") // After conversion Sun Sep 27 11:30:00 GMT+05:30 2020
val VancouverMnight = DateTime(Vancouver).withTimeAtStartOfDay().millis
Log.d("Datey2", "MidNight $VancouverMnight") // MidNight Sun Sep 27 00:00:00 GMT+05:30 2020
Output:
Before conversion Mon Sep 28 00:00:00 GMT+5:30 2020
After conversion Sun Sep 27 11:30:00 GMT+05:30 2020 // Note the GMT+5:30 in vacouver time
MidNight Sun Sep 27 00:00:00 GMT+05:30 2020
Then I convert these into milliseconds as follows
Log.d("Datey2", "After conversion {$VancouverMnight.time}") // using time function gives output in milliseconds
But when I convert those Vancouver outputs to milliseconds, I get the following:
1601186400000 // Sep 26 23:00:00 2020 - Goes 2 days before the given time
1601145000000 // Sep 26 11:30:00 2020
What I need:
Sep 27 11:30:00 2020
Sep 27 00:00:00 2020 (I need these in milliseconds)
Since you are using Joda-Time, I recommend you either stick to that or move on to java.time, the modern Java date and time API. Stay away from Date and SimpleDateFormat. They are poorly designed and long outdated, and there is absolutely no reason why you should want to touch them.
For a Joda-Time solution in Java because this is what I can write and run:
DateTimeZone vancouverTimeZone = DateTimeZone.forID("America/Vancouver");
DateTimeFormatter dateOutputFormat = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss")
.withZone(vancouverTimeZone);
DateTime today = new DateTime().withTimeAtStartOfDay();
System.out.println("Today: " + today);
System.out.println("Today as seen in Vancouver: " + today.toString(dateOutputFormat));
long millisBeforeConversion = today.getMillis();
System.out.println("Millis before conversion: " + millisBeforeConversion);
DateTime vancouverMidnight = today.withZone(vancouverTimeZone)
.withTimeAtStartOfDay();
long millisAfterConversion = vancouverMidnight.getMillis();
System.out.println("Millis after conversion: " + millisAfterConversion);
Output when running today in Asia/Kolkata time zone:
Today: 2020-09-29T00:00:00.000+05:30
Today as seen in Vancouver: 2020/09/28 11:30:00
Millis before conversion: 1601317800000
Millis after conversion: 1601276400000
A day has passed since you asked your questions, so you cannot compare the millisecond values from my output with your own from the question, but you can verify that they agree with what you would want for today (already September 29 in India).
Note that the count of milliseconds since the epoch is independent of time zone. So whether you get the milliseconds before or after conversion to America/Vancouver time zone makes no difference.
If you want to move on to java.time, follow the good answer by Arvind Kumar Avinash.
The problem is that you are trying to write the java.util.Date object directly which outputs the value of java.util.Date#toString. Note that a date-time object is supposed to store the information about date, time, time-zone etc. but not about the formatting. The java.util.Date object is not a real date-time object like the modern date-time classes; rather, it represents the milliseconds from the Epoch of January 1, 1970. When you print an object of java.util.Date, its toString method returns the date-time calculated from this milliseconds value. Since java.util.Date does not have time-zone information, it applies the time-zone of your JVM and displays the same. If you need to print the date-time in a different time-zone, you will need to set the time-zone to SimpleDateFormat and obtain the formatted string from it e.g.
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ssZ z");
Date date = new Date();
// Date and time in India
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
// Output to be written to the log file
System.out.println(sdf.format(date));
// Date and time in Vancouver
sdf.setTimeZone(TimeZone.getTimeZone("America/Vancouver"));
// Output to be written to the log file
System.out.println(sdf.format(date));
}
}
Output:
2020/09/29 17:57:06+0530 IST
2020/09/29 05:27:06-0700 GMT-07:00
I recommend you switch from the outdated and error-prone java.util date-time API and SimpleDateFormat to the modern java.time date-time API and the corresponding formatting API (package, java.time.format). Learn more about the modern date-time API from Trail: Date Time. If your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Using the modern date-time API:
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ssZ z");
// Date and time in India
ZonedDateTime zdtNowIST = LocalDate.now().atStartOfDay((ZoneId.of("Asia/Calcutta")));
// Output in the default format
System.out.println(zdtNowIST);
// Output in the custom format
System.out.println(zdtNowIST.format(dtf));
// Date and time in Vancouver
ZonedDateTime zdtNowVancouver = zdtNowIST.withZoneSameInstant(ZoneId.of("America/Vancouver"));
// Output in the default format
System.out.println(zdtNowVancouver);
// Output in the custom format
System.out.println(zdtNowVancouver.format(dtf));
}
}
Output:
2020-09-29T00:00+05:30[Asia/Calcutta]
2020/09/29 00:00:00+0530 IST
2020-09-28T11:30-07:00[America/Vancouver]
2020/09/28 11:30:00-0700 GMT-07:00
I do not know Kotlin but I believe you should be able to use Java code directly in Kotlin. If not, at least you should be able to convert it using Kotlin syntax.
I am trying to display a timestamp as "Sat Dec xx ww:yy:zz IST YYYY".
When i run this code snippet in android device i get result as "Sat Dec xx ww:yy:zz GMT+05:30 YYYY".
Date dd = new Date();
String s = dd.toString();
The below snippet also gives the time in GMT+05:30 format.
String timeZone =
Calendar.getInstance().getTimeZone().getDisplayName(false, TimeZone.SHORT);
TimeZone can be any of the zones as per mob. location. So hard coding doesn't make any sense.
How can i get the result in the desired format?
Use SimpleDateFormat to explicitly get "Sat Dec xx ww:yy:zz" part and "YYYY" part
Store them up in variables
get the time zone String using
String timeZone =
Calendar.getInstance().getTimeZone().getID();
then use
String.format("%s %s %s", firstPart, timeZone, yearPart);
update: I thought the Android version was to blame, but it turns out it is the user-timezone
This code produces incorrect output when my tablets time is in Central European time (+2 in summer time):
SimpleDateFormat dateTimeFormatter = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss Z", Locale.GERMAN);
Date testDate = dateTimeFormatter
.parse("2999-01-01 00:00:00 +0100");
Log.v(TAG, "test 1 " + testDate);
testDate = dateTimeFormatter.parse("2099-01-01 00:00:00 +0100");
Log.v(TAG, "test 2 " + testDate);
"test 1 Mon Dec 31 23:19:32 CET 2998"
"test 2 Thu Jan 01 00:00:00 CET 2099"
There is a time difference. Why the 40 minutes and some seconds difference on the larger date?
The bug is not present when I put my tablet in (most) other timezones. Something to do with timezones that have dailight saving hours?
Guess I cannot overcome this bug, I've built my own date parser.
Update: my own parser has the same problem
My current solution is just not using these large dates. If date > 100 years in future, I set it to 100 years in the future.
I am working on android project. I am setting date and time but it is displaying in the following format.
Mon Nov 19 11:00:00 GMT+05:30 2012
In my database table the datetime column datatype is datetime. So how can I change the above output to datetime format to store it in database.
Any help in this regard will be thankful.
you should probably read a bit about SimpleDateFormat, it's the way to parse String into Date.
the way to do this is to create a pattern for the formatter, then create the formatter and after that parse the Strings.
String pattern = "EEE, dd MMM yyyy HH:mm:ss z";
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date myDate = format.parse(str);
I have a twitter feed in setup in my app.
But it the date isn't formatted right.
It now displays like this : Sat, 25 feb 2012 22:39:32 +0000 but I would like it to be in dutch and like this: 22:39u 25 februari 2012 (Dutch format and naming).
Or maybe if possible: "about 2 hours ago"
I used the code of this tutorial:
http://codehenge.net/blog/2011/05/android-programming-tutorial-a-simple-twitter-feed-reader/
And I added:
((JSONObject)t).get("profile_image_url").toString()
For those who are still looking for solution:
Step-1 First we need to convert the twitter feed format to Date Obj. Like from twitter JSON response we are getting the created at value as:--
Sat Apr 02 17:14:28 +0000 2016
The corresponding format will be "EEE MMM dd hh:mm:ss Z yyyy"
Refer here for how to use formatting pattern letters
So the code to cobert it to date object will be:
//Existing Format
SimpleDateFormat createdDateFormat = new SimpleDateFormat("EEE MMM dd hh:mm:ss Z yyyy");;
Date dateObj = createdDateFormat.parse(date);
Step-2 Convert this date Obj to your required format using new format pattern as below:
//changing to new format
createdDateFormat = new SimpleDateFormat("MMM dd,yyyy hh:mm a");
date = createdDateFormat.format(dateObj);
The final output is:-
Apr 03,2016 03:06 AM
As the comments say on that page, you need to use SimpleDateFormat