Android JodaTime convert UTC to User's time - java

I am stuck while solving this naive scenario. Here is what I designed to convert UTC to local time.
public static DateTime timezoneAwareDate(Date date){
DateTime input = new DateTime(date,DateTimeZone.UTC);
DateTime output = input.withZone(DateTimeZone.getDefault());
Log.d(niftyFunctions.LOG_TAG,new SimpleDateFormat("yyyy-mmm-dd hh:mm").format(output.toDate()));
return output;
}
Here is what my input date looks like in UTC, coming from server:
2015-07-28 16:30
But here is what I am getting on my phone which is in IST from Log.d statement:
2015-030-28 07:30
I am going crazy about what's actually happening. Any help?

So I went with Joda-less solution using just the native libs. Here is the function
/**
* Returns localtime for UTC
*
* #param date
* #return
*/
public static Date timezoneAwareDate(String date){
// create simpledateformat for UTC dates in database
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date output;
// parse time
try{
output = simpleDateFormat.parse(date);
}catch (Exception e){
// return current time
output = new Date();
}
return output;
}

Related

convert Date to Time with java

I want to convert a variable of type Date into Time format . I tried to use SimpleDateFormat but without success .
I used the SimpleDateFormat for converting the String into Date.
public static String convDataToString (Date dataconv)
{
SimpleDateFormat formattoData = new SimpleDateFormat("yyyy-MM-dd");
String data = "";
try{
dataconv = formattoData.parse(data);
System.out.println(formattoData.format(dataconv));
}
catch(Exception e){
e.getMessage();
}
return formattoData.format(dataconv);
}
But I need to convert Date into Time format.
In java.util package we can find Date class which encapsulates date and time. If you try new Date(), you get both date and time for the current timestamp. But Calendar class (java.util.Calendar) provides many tools for manipulations of date and time.

Converting a Date to a new TimeZone in Java

Converting a Java Date object to a specific ("target") time zone is a question that has been asked numerous times before in StackOverflow and the suggested solutions apparently are:
Adjust the time (milliseconds) value of the Date object by the timezone offset
Use SimpleDateFormat (with the timezone) to produce the desired date as a String
However, there seems to be no "plain Java" solution that parses a date string (with or without timezone) into a Date object and then adjusts a corresponding Calendar object to the target timezone, so that the "converted" date behaves in all cases in the correct way (e.g., when using the Calendar object to retrieve the year of the date).
The main issue is that, reasonably, when the SimpleDateFormat pattern used to parse the date string does not have a timezone, the system assumes that the time is in the parsing system's timezone. If, however, the pattern does have a timezone, the time is counted from UTC. So, what is needed is essentially an indication as to whether the original date string corresponds to a pattern with or without a timezone, which apparently cannot be done without analyzing the pattern itself.
The attached source code of the TimezoneDate class demonstrates the discrepancies.
Here is the output from running the main() method for 2 "original dates", the first without and the second with a timezone, when they are converted to UTC on a machine running on Pacific Standard Time (PST):
Original date: 20/12/2012 08:12:24
Formatted date (TZ): 20/12/2012 16:12:24
Formatted date (no TZ): 20/12/2012 08:12:24
Calendar date: 20/12/2012 16:12:24
Expected date: 20/12/2012 08:12:24
Original date: 20/10/2012 08:12:24 +1200
Formatted date (TZ): 19/10/2012 20:12:24
Formatted date (no TZ): 19/10/2012 13:12:24
Calendar date: 19/10/2012 20:12:24
Expected date: 19/10/2012 20:12:24
The correct operation is to have the "Formatted" and "Calendar" strings identical to the "Expected date" for each of the 2 example date strings ("original dates").
Apparently one needs to make a distinction between the case where the date string contains a timezone symbol (TZ) and the case where it does not (no TZ), but this means knowing the SimpleDateFormat pattern beforehand, which is not possible when handling a Date object and not the original string.
So, the question is really about whether a generic "plain Java" (no third party libraries) solution exists that does not require prior knowledge of the pattern and works correctly with the corresponding Calendar object.
Following is the full source code of the TimezoneDate class.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class TimezoneDate
{
private final Date time;
private final TimeZone timezone;
private final Calendar calendar;
/**
* Creates a wrapper for a {#code Date} object that is converted to the
* specified time zone.
*
* #param date The date to wrap
* #param timezone The timezone to convert to
*/
public TimezoneDate(Date date, TimeZone timezone)
{
this.calendar = TimezoneDate.getPlainCalendar(date, timezone);
this.time = this.calendar.getTime();
this.timezone = timezone;
}
private static Calendar getPlainCalendar(Date date, TimeZone timezone)
{
Calendar calendar = Calendar.getInstance(timezone);
calendar.setTime(date);
return calendar;
}
private static Calendar getAdjustedCalendar(Date date, TimeZone timezone)
{
long time = date.getTime();
time = time + timezone.getOffset(time) - TimeZone.getDefault().getOffset(time);
date = new Date(time);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
public int getYear()
{
return this.calendar.get(Calendar.YEAR);
}
public int getMonth()
{
return (this.calendar.get(Calendar.MONTH)+1);
}
public int getMonthDay()
{
return this.calendar.get(Calendar.DAY_OF_MONTH);
}
public int getHour()
{
return this.calendar.get(Calendar.HOUR_OF_DAY);
}
public int getMinutes()
{
return this.calendar.get(Calendar.MINUTE);
}
public int getSeconds()
{
return this.calendar.get(Calendar.SECOND);
}
public String toCalendarDate() // The date as reported by the Calendar
{
StringBuilder sb = new StringBuilder();
sb.append(this.getMonthDay()).append("/").append(this.getMonth()).
append("/").append(this.getYear()).append(" ").
append(this.getHour()).append(":").append(this.getMinutes()).
append(":").append(this.getSeconds());
return sb.toString();
}
public String toFormattedDate(boolean addTimezone) // The formatted date string
{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
if (addTimezone)
{
sdf.setTimeZone(this.timezone);
}
return sdf.format(this.time);
}
public static void main(String[] args) throws Exception
{
// Each data "vector" contains 3 strings, i.e.:
// - Original (example) date
// - SimpleDateFormat pattern
// - Expected date after converting the original date to UTC
String[][] data = new String[][]
{
{"20/12/2012 08:12:24", "dd/MM/yyyy' 'HH:mm:ss", "20/12/2012 08:12:24"},
{"20/10/2012 08:12:24 +1200", "dd/MM/yyyy HH:mm:ss Z", "19/10/2012 20:12:24"}
};
Date originalDate;
TimezoneDate timezoneDate;
SimpleDateFormat format;
TimeZone UTC = TimeZone.getTimeZone("UTC");
for (String[] vector:data)
{
format = new SimpleDateFormat(vector[1]);
originalDate = format.parse(vector[0]);
timezoneDate = new TimezoneDate(originalDate, UTC);
System.out.println();
System.out.println("Original date: " + vector[0]);
System.out.println("Formatted date (TZ): " + timezoneDate.toFormattedDate(true));
System.out.println("Formatted date (no TZ): " + timezoneDate.toFormattedDate(false));
System.out.println("Calendar date: " + timezoneDate.toCalendarDate());
System.out.println("Expected date: " + vector[2]);
}
}
}
Joda-Time
Rather than use Java's Date you should use the Joda-Time DateTime class. This allows you to carry out timezone operations in a very simple fashion, using the withTimezone() and withTimezoneRetainFields() methods depending on your particular requirements.

How to convert "MM-dd-yyyy hh:mm" String date format to GMT format?

My Date format is like as "MM-dd-yyyy hh:mm" its not current date ,I have to send this date
to server but before send it need to change this date to GMT format but when I change by following code:
private String[] DateConvertor(String datevalue)
{
String date_value[] = null;
String strGMTFormat = null;
SimpleDateFormat objFormat,objFormat1;
Calendar objCalendar;
Date objdate1,objdate2;
if(!datevalue.equals(""))
{
try
{
//Specify your format
objFormat1 = new SimpleDateFormat("MM-dd-yyyy,HH:mm");
objFormat1.setTimeZone(Calendar.getInstance().getTimeZone());
objFormat = new SimpleDateFormat("MM-dd-yyyy,HH:mm");
objFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
//Convert into GMT format
//objFormat.setTimeZone(TimeZone.getDefault());//);
objdate1=objFormat1.parse(datevalue);
//
//objdate2=objFormat.parse(datevalue);
//objFormat.setCalendar(objCalendar);
strGMTFormat = objFormat.format(objdate1.getTime());
//strGMTFormat = objFormat.format(objdate1.getTime());
//strGMTFormat=objdate1.toString();
if(strGMTFormat!=null && !strGMTFormat.equals(""))
date_value = strGMTFormat.split(",");
}
catch (Exception e)
{
e.printStackTrace();
e.toString();
}
finally
{
objFormat = null;
objCalendar = null;
}
}
return date_value;
}
its not change in required format ,I have tried by above code first try to get current timeZone and after that try change string date into that timezone after that convert GMT.
anyone guide me.
thanks in advance.
Try the below code. The first sysout prints the date object which picks up default OS timezone i.e. IST in my case. The second sysout prints the date in the required format after converting the date to GMT timezone.
If you know the timezone of your date string then set that in the formatter. I assumed you need the same date format in the GMT timezone.
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy,HH:mm");
Date date = format.parse("01-23-2012,09:40");
System.out.println(date);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(format.format(date));
you need to use TimeZone's getRawOffset() method:
Date localDate = Calendar.getInstance().getTime();
TimeZone tz = TimeZone.getDefault();
Date gmtDate = new Date(date.getTime() - tz.getRawOffset());
it
returns the amount of time in milliseconds to add to UTC to get standard time in this time zone. Because this value is not affected by daylight saving time, it is called raw offset.
If you want to consider DST as well (you might want this ;-) )
if (tz.inDaylightTime(ret)) {
Date dstDate = new Date(gmtDate.getTime() - tz.getDSTSavings());
if (tz.inDaylightTime(dstDate) {
gmtDate = dstDate;
}
}
The last check is needed if you are right on the edge of a summer time change and would, for instance, go back into standard time by the conversion.
Hope that helps,
-Hannes

Convert Unix time into readable Date in Java

What is the easiest way to do this in Java? Ideally I will be using Unix time in milliseconds as input and the function will output a String like
November 7th, 2011 at 5:00 PM
SimpleDateFormat sdf = new SimpleDateFormat("MMMM d, yyyy 'at' h:mm a");
String date = sdf.format(myTimestamp);
I wanted to convert my unix_timestamps like 1372493313 to human readable format like Jun 29 4:08.
The above answered helped me for my Android app code. A little difference was that on Android it recommends to use locale settings as well, and my original unix_timestamp was in seconds, not milliseconds, and Eclipse wanted to add try/catch block or throw exception. So my working code has to be modified a bit like this:
/**
*
* #param unix_timestamp
* #return
* #throws ParseException
*/
private String unixToDate(String unix_timestamp) throws ParseException {
long timestamp = Long.parseLong(unix_timestamp) * 1000;
SimpleDateFormat sdf = new SimpleDateFormat("MMM d H:mm", Locale.CANADA);
String date = sdf.format(timestamp);
return date.toString();
}
And here is the calling code:
String formatted_timestamp;
try {
formatted_timestamp = unixToDate(unix_timestamp); // timestamp in seconds
} catch (ParseException e) {
e.printStackTrace();
}
java.util.Date date = new java.util.Date((long) time * 1000L);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

Getting device's local timezone

2010-06-14 02:21:49+0400 or 2010-06-14 02:21:49-0400
is there a way to convert this string to the date according to the local machine time zone with format 2010-06-14 02:21 AM
Adding to what #org.life.java and #Erica said, here's what you should do
String dateStr = "2010-06-14 02:21:49-0400";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
TimeZone tz = TimeZone.getDefault();
sdf.setTimeZone(tz);
Date date = sdf.parse(dateStr);
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
String newDateStr = sdf.format(date);
System.out.println(newDateStr);
Then newDateStr will be your new date formatted string.
UPDATE #xydev, the example I gave you works, see the full source code below:
/**
*
*/
package testcases;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/**
* #author The Elite Gentleman
*
*/
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String dateStr = "2010-06-14 02:21:49-0400";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
TimeZone tz = TimeZone.getDefault();
sdf.setTimeZone(tz);
Date date = sdf.parse(dateStr);
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
String newDateStr = sdf.format(date);
System.out.println(newDateStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Output: 2010-06-14 08:21:49 AM
Using SimpleDateFormat
String string1 = "2010-06-14 02:21:49-0400";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ")
sdf.setTimeZone(tz);
Date date = sdf.parse(string1);
Note: I am not sure the same class is available in andriod.
You can do all sorts of fancy formatting and localisation of dates using the DateFormat class. There's very good, complete documentation at the start of the API page here:
http://download.oracle.com/javase/1.4.2/docs/api/java/text/DateFormat.html
Most regular cases can be handled with the built in SimpleDateFormat object. Its details are here:
http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
The SimpleDateFormat output pattern string for the example you have above would be:
yyyy-MM-dd hh:mm a
Be careful that if you are running on the emulator your timezone is always GMT. I just spent 2 hours in trying to understand why my application does not give me the right time (the one my computer displays) until I realized it is because of the emulator.
To check you are running on the emulator use
if (Build.PRODUCT.contains("sdk")){
// your code here for example if curtime has the emulator time
// since midnight in milliseconds then
curtime += 2 * 60 * 60 * 1000; // to add 2 hours from GMT
}

Categories

Resources