Android Date timezone issues - java

a). I have 3 strings representing the date, time and timeZone; ex.:
String date = "2012-09-04";
String time = "01:30:17";
String timeZone = "UTC";
and I want to create a date using these strings.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
Date createdDate = formatter.parse(date + " " + time + " " + timeZone);
doesn't work - I get the message "Unparseable date".
b). How can I get the Android device date in a specific timeZone?
I found just a way of converting current time to, for example, UTC timeZone:
Calendar cldr = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateInUTCTimeZone = sdf.format(cldr.getTime());
but I want the result to be a Date object.

The string "UTC" is nothing that the Date parser can recognize. If you need to use this constant for defining UTC, then the following date format should work for you
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss 'UTC'");
but I'd strongly recommend tu use the rfc3990 standard:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
and then represent your date as the following string (2012-09-04T13:24:59Z).
Finally if you want to represent a date which is in UTC to a certain time zone, use the following before formatting:
sdf.setTimeZone(TimeZone.getDefault()); //Choose the TimeZone you need

Related

How can i get the date formate "11, jul,Tue " in java?

i want to select the date format from calendar which display date as "11 Jul,Tue " in java. How can i get convert date into this format.
You use the SimpleDateFormat class to get what you want. You can use a format of "dd, MMM, EEE" The dd gives you the day as a number; the MMM the month; and the EEE the day as text. Here is the Ocacle documentation for SimpleDateFormat
So it would work as follows
SimpleDateFormat sdf = new SimpleDateFormat("dd, MMM, EEE");
System.out.println(sdf.format( new Date()) );
That would print out the current date as 11, Jul, Tue You can get your Date object from the Calender using getTime() So:
Calender yourCalenderObject;
Date date = yourCalenderObject.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("dd, MMM, EEE");
System.out.println( sdf.format(date) );
You can format date into string that way.
String pattern = "dd, MMM, EEE";
System.out.println(DateTimeFormatter.ofPattern(pattern).format(LocalDateTime.now())); // java 8
System.out.println(new SimpleDateFormat(pattern).format(new Date())); // java 7 and lower

Convert date with known timezone to UTC date

Date and Time Conversion has always been my weak link. I have the following values in string format:
String date="2015-08-21 03:15" and timezone for this date is
String timeZone="GMT+05:30";
Now I need to covert this date, for which I already know the timezone, to UTC date.
If you are given time in "GMT+05:30" timezone next code will convert it to UTC timezone:
String strDate = "2015-08-21 03:15";
String timeZone="GMT+05:30";
String format = "yyyy-MM-dd HH:mmz";
SimpleDateFormat formatter = new SimpleDateFormat(format);
Date dateStr = formatter.parse(strDate+timeZone);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String formattedDate = formatter.format(dateStr);
System.out.println("UTC datetime is: "+formattedDate);
You can try like this:
Approach 1: Using Java Date:
//Your input date string
String date="2015-08-21 03:15";
// date format your string
String format = "yyyy-MM-dd HH:mm";
//Create SimpleDateFormat instance
SimpleDateFormat sdf = new SimpleDateFormat(format);
// Convert Local Time to UTC
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
//parse your input date string to UTC date
Date gmtTime = new Date(sdf.parse(date));
Approach 2: Using Joda time (recommended)
String dateString = "2015-08-21 03:15:00+5:30";
String pattern = "yyyy-MM-dd HH:mm:ssZ";
DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);
DateTime dateTime = dtf.parseDateTime(dateString);
System.out.println(dateTime);
Since you only want a Java-8-solution:
String input = "2015-08-21 03:15";
String offsetInfo = "GMT+05:30";
LocalDateTime ldt =
LocalDateTime.parse(input, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm"));
ZoneOffset offset =
ZoneOffset.of(offsetInfo.substring(3)); // GMT-prefix needs to be filtered out
LocalDateTime result =
ldt.atOffset(offset).withOffsetSameInstant(ZoneOffset.UTC).toLocalDateTime();
System.out.print(result); // output: 2015-08-20T21:45
A Date in java represents the number of milliseconds since 1970. This number alone has no specific time zone. This means if you create a Date with new Date() you get the current milliseconds since 1970 and if you call toString on it this value gets represented in your current locale timezone. The actual time this number represents is time zone specific. This is the reason why you can set a TimeZone on Calendar and Format classes.
To instantiate a calendar with a specific TimeZone you can do this:
public static Calendar getUtcCalendar() {
GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
}
So to convert a Date to a specific time in UTC TimeZone:
Calendar calendar = getUtcCalendar();
calendar.setTime(date);
return calendar;
You can see:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
Date date = null;
try {
//Here you say to java the initial timezone. This is the secret
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
date = sdf.parse(review);
} catch (ParseException e) {
e.printStackTrace();
}
//Here you set to your timezone
sdf.setTimeZone(TimeZone.getDefault());
System.out.println(sdf.format(date));

Get the time of other TimeZone by date string, the result is wrong

I only have a date string, and I want to see the time in other TimeZone by it. So I did it like that:
String dateStr = "2014-05-15 16:14:58 PM";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
sdf.setTimeZone(TimeZone.getTimeZone("America/Denver"));
Date date = sdf.parse(dateStr);
System.out.println(date);
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
System.out.println(sdf1.format(date));
This is the current TimeZone in my computer:
The result that the code ran was that:
Fri May 16 06:14:58 CST 2014
2014-05-16 06:14:58 AM
The result is wrong, I had the right result by changing the TimeZone to "America/Denver" in my computer, and I saw that:
America/Denver —— 2014-05-15 02:14:58 AM
I don't know why it likes that?
But if I had a Date not a date String, I do that :
public static String getFormatedDateString(String _timeZone) {
TimeZone timeZone = null;
if (StringUtils.isEmpty(_timeZone)) {
timeZone = TimeZone.getDefault();
} else {
timeZone = TimeZone.getTimeZone(_timeZone);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
sdf.setTimeZone(timeZone);
// TimeZone.setDefault(timeZone);
return sdf.format(new Date());
}
System.out.println("America/Denver —— " + getFormatedDateString("America/Denver"));
The result likes that:
------Asia/Shanghai------
2014-05-15 16:32:04 PM (current date)
America/Denver —— 2014-05-15 02:32:04 AM
This result is right.
So I was confused, I could't find the problem when I just have a date string and I want to know the time of other TimeZone. Could any body help me?
Date object in Java is independent of the concept of timezone.
What you want to do get the equivalent time in another timezone of a date string which is 'supposed' to be in your own timezone.
However, 2nd point appears backwards in your code:
String dateStr = "2014-05-15 16:14:58 PM";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
sdf.setTimeZone(TimeZone.getTimeZone("America/Denver"));
Date date = sdf.parse(dateStr);
What these 4 lines do is consider the date string as a point in time in "America/Denver" timezone.
When you parse it to the date object, it would give you the equivalent time in your own timezone.
You want it the other way round:
Hence staying close to your code (you can just use a single SimpleDateFormat instance effectively, which you can figure out later),
Drop the setTimezone on the first sdf:
String dateStr = "2014-05-15 16:14:58 PM";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
//sdf.setTimeZone(TimeZone.getTimeZone("America/Denver"));
Date date = sdf.parse(dateStr);
System.out.println(date);
Add the same setTimezone to the other sdf:
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
sdf1.setTimeZone(TimeZone.getTimeZone("America/Denver"));
System.out.println(sdf1.format(date));
Now, you are parsing your date String to a date in your current (JVM's) timezone. Then format the same date to a different timezone's String.
Output I get with the changed code (my JVM's timezone being IST):
Thu May 15 16:14:58 IST 2014 // Parsed the date string in IST
2014-05-15 04:44:58 AM // Equivalent time in Denver

How to parse values returned by getDate() in java?

I have created a web service which returns the date of an event which is initially captured by the getDate() function. I want the date returned by this function (something along this format : 2013-05-17 14:52:00.943) to be parsed and shown to the user in the DD-MM-YYYY format.
Any suggestions? I haven't found any solution along this direction yet.
I have tried this code and it's work fine for me,Please Try my code below: Please upvote to Tarun also coz he gave almost right answer.just he did mistake that he passes cal.getTime() method instead of pDate
String formatDate = p.format(pDate);
and second mistake in format like"DD-MM-YYYY" but actual format is:
"dd-MM-yyyy" not "DD-MM-YYYY"
I have done changes in it and modify it.
String dateStr = "2013-05-16 14:52:00.943";
SimpleDateFormat c = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S"); // your web service format
Date pDate = c.parse(dateStr);
SimpleDateFormat p = new SimpleDateFormat("dd-MM-yyyy"); // your required format
String formatDate = p.format(pDate); // convert it in your required format
SimpleDateFormat formatter = new SimpleDateFormat("EEEE"); // Day format as you want EEE for like "Sat" and EEEE for like "Saturday"
String Day = formatter.format(pDate); // This will give you a day as your selected format
System.out.println("Date & Day>>>"+formatDate+" "+Day);
// For GMT format your format should be like this: "2013-05-16 14:52:00.943 GMT+05:30"
// Give it to me in GMT time.
c.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
System.out.println("GMT time: " + c.format(pDate));
Output:
Date & Day>>>16-05-2013 Thursday
GMT time: 2013-05-16 02:52:00.943 Greenwich Mean Time
Joda time:
you can download 2.0 jar file of joda time from here:
DateTimeFormatter jodaFormatter = ISODateTimeFormat.dateTime();
DateTime jodaParsed = jodaFormatter
.parseDateTime("2013-05-17T16:27:34.9+05:30");
Date date2 = jodaParsed.toDate();
System.out.println("Date & Day:" + jodaParsed.getDayOfMonth() + "-" + jodaParsed.getMonthOfYear() + "-" + jodaParsed.getYear() + " " + jodaParsed.getHourOfDay() + ":" + jodaParsed.getMinuteOfHour()+" "+jodaParsed.dayOfWeek().getAsText());
output:
Date & Day:17-5-2013 16:27 Friday
Hope it will work for you.
String dateStr = "2013-05-17 14:52:00.943";
SimpleDateFormat c = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
Date pDate = c.parse(dateStr);
SimpleDateFormat p = new SimpleDateFormat("dd-MM-yyyy");
String formatDate = p.format(pDate);
You can use Joda Time if you have colon in time offset.
DateTimeFormatter jodaFormatter = ISODateTimeFormat.dateTime();
DateTime jodaParsed = jodaFormatter.parseDateTime("2013-05-17T16:27:34.9+05:30");
Date date = jodaParsed.toDate();
Calendar c = Calendar.getInstance();
c.setTime(date);
c.get(Calendar.DATE));
More info about joda can be found here.
Use a SimpleDateFormat to parse the date and then print it out with a SimpleDateFormat withe the desired format.
Example:
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MM-yyyy");
Date date = format1.parse("05/18/2013");
System.out.println(format2.format(date));
Output:
11-05-2013
Edit:
Calendar cal = Calendar.getInstance();
cal.setTime(specific_date);
int dayOfMonth = cal.get(Calendar.DAY_OF_WEEK);
String dayOfMonthStr = String.valueOf(dayOfMonth);

Parse a date with the timezone "Etc/GMT"

My first attempt was:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
Date date = formatter.parse(string);
It throws ParseException, so I found this hack:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
TimeZone timeZone = TimeZone.getTimeZone("Etc/GMT");
formatter.setTimeZone(timeZone);
Date date = formatter.parse(string);
It did not work either, and now I'm stuck. It parses without problems if I just change the timezone to "GMT".
edit: An example string to parse would be "2011-11-29 10:40:24 Etc/GMT"
edit2: I would prefer not to remove timezone information completely. I am coding a server that receives the date from an external user, so perhaps other dates will have other timezones.
To be more precise: This specific date I receive is from the receipt from the apple server after making an in app purchase on an iphone app, but I could also receive dates from other sources.
Don't know if this question is still relevant to you, but if you use Joda time, this'll work:
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss ZZZ").parseDateTime(s)
Without Joda time the following will work (bit more work though):
String s = "2011-11-29 10:40:24 Etc/GMT";
// split the input in a date and a timezone part
int lastSpaceIndex = s.lastIndexOf(' ');
String dateString = s.substring(0, lastSpaceIndex);
String timeZoneString = s.substring(lastSpaceIndex + 1);
// convert the timezone to an actual TimeZone object
// and feed that to the formatter
TimeZone zone = TimeZone.getTimeZone(timeZoneString);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter.setTimeZone(zone);
// parse the timezoneless part
Date date = formatter.parse(dateString);
It didn't work for me either the thing is I tried setting TimeZone of SimpleDateFormatter to "Etc/GMT" and then formatted a new date here is the output:
2011-11-30 10:46:32 GMT+00:00
So Etc/GMT is being translated as GMT+00:00
If you really want to stick to parse "2011-09-02 10:26:35 Etc/GMT" then following will help too without even considering explicit Timezone change:
java.text.SimpleDateFormat isoFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss 'Etc/GMT'");
isoFormat.parse("2010-05-23 09:01:02 Etc/GMT");
Works fine.
Following code is working for me
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Etc/GMT"));
try { System.out.println( sdf.parse("2011-09-02 10:26:35 Etc/GMT") );
} catch (ParseException e){
e.printStackTrace();
}

Categories