How do I get date & time in a different time zone? - java

I am using Indigo Service Release 2. I have written following code:
TimeZone calcutta = TimeZone.getTimeZone("Asia/Calcutta");
Date now = new Date();
DateFormat format =
DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
format.setTimeZone(calcutta);
jlabel_IndiaTime.setText((format.format(now).toString()));
It is showing Monday, September 17,2012 1:13:23 PM IST, but in India the time is 10:14AM. I am trying this from New York. Could anyone please help me?

Here's some example code. I'm explicitly setting my server's default time zone to NY time, but you may want to follow Jon Lin's hint and determine for certain the default time zone of your own server. For example, if you're in NY, but are using a server hosted in SF and using Pacific time, then that could account for a 3 hour difference from the expected time in any zone.
public void testTodayInIndia() {
// For demonstration, make my system act as though it's in New York
TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
long oneDay = 86400000;
long fourYears = (365 * 4 + 1) * oneDay;
// Calculate 42 years after 1/1/1970 UTC
Date now = new Date(fourYears * 10 + oneDay * 365 * 2 + 1);
TimeZone calcutta = TimeZone.getTimeZone("Asia/Kolkata");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Since unspecified, this output will show the date and time in New York
assertEquals("2011-12-31 19:00:00", formatter.format(now));
// After setting the formatter's time zone, output reflects the same instant in Calcutta.
formatter.setTimeZone(calcutta);
assertEquals("2012-01-01 05:30:00", formatter.format(now));
}

You can use SimpleDateFormat and Date classes such as below:
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println(simpleDateFormat.format(date));
There are different time zones you can replace with "America/New_York" such "Asia/Calcutta".

Related

GWT - Displayed date is decremented one day

The server I use is in Melbourne, Australia. I have reports from Perth, Australia that the date displayed is decremented by one day (i.e., 2003-10-31 is displayed as 2003-10-30). In my readings I find that I need to set the time zone. They say do not use the two/three letter time zone use the full time zone. However, I can not find the full time zone for Melbourne, Australia. Can anyone help with this please?
The code I have come up with is:
//Display the DOB
DateTimeFormat fmt = DateTimeFormat.getFormat("yyyy-MM-dd australiaMelbourne");
String stringDOB = fmt.format(ythMmbrSectDtls.getDob());
Label dateLblDOB = new Label(stringDOB);
dateLblDOB.setStyleName("gwt-Label-Login");
dateLblDOB.setWidth("100px");
flexTable.setWidget(row, 3, dateLblDOB);
The code should be (on the server side):
while (result.next()) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(result.getDate("dob"));
TimeZone timeZone = TimeZone.getDefault();
calendar.setTimeZone(timeZone);
java.sql.Date javaSqlDateDOB = new java.sql.Date(calendar.getTime().getTime());
VenturerSectDtls venturerSectDtls = new VenturerSectDtls(
result.getString("cdID"),
null,
result.getString("surname"),
result.getString("firstName"),
javaSqlDateDOB,
//result.getDate("dob"),
The full time zone format is Continent/City so in your case Australia/Melbourne.
For further Information see: http://tutorials.jenkov.com/java-date-time/java-util-timezone.html
Use SimpleDateFormat instead of DateTimeFormat
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
Please check the documentation for SimpleDateFormat here
Java 6 : http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
Java 7 : http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Java convert data/time between timezone is inaccurate

TimeZone.setDefault(TimeZone.getTimeZone("Europe/Moscow"));
System.out.println("Default Timezone: " + TimeZone.getDefault());
String date = "08/04/2016 00:00:00";
SimpleDateFormat simpleDateFormatMoscow = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date moscowDt = simpleDateFormatMoscow.parse(date);
System.out.println("Moscow Date: " + simpleDateFormatMoscow.format(moscowDt));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Bangkok"));
System.out.println("Bangkok Date: " + simpleDateFormat.format(moscowDt));
Calendar calendar = new GregorianCalendar();
calendar.setTime(moscowDt);
calendar.setTimeZone(TimeZone.getTimeZone("Asia/Bangkok"));
System.out.println("Bangkok Date: " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Test Timezone");
System.out.println(TimeZone.getTimeZone("America/New_York"));
System.out.println(TimeZone.getTimeZone("Europe/Moscow"));
System.out.println(TimeZone.getTimeZone("Asia/Bangkok"));
I tried to use the code this snippet to convert date/time between Moscow and Bangkok. The result is as followed:
Default Timezone:
sun.util.calendar.ZoneInfo[id="Europe/Moscow",offset=14400000,dstSavings=0,useDaylight=false,transitions=78,lastRule=null]
Moscow Date: 08/04/2016 00:00:00
//util date/time
Bangkok Date: 08/04/2016 03:00:00
//joda time
Bangkok Date: 08/04/2016 03:00:00
However, when I convert date/time using https://singztechmusings.wordpress.com/2011/06/23/java-timezone-correctionconversion-with-daylight-savings-time-settings/ or google the time is
Moscow Date: 08/04/2016 00:00:00
Bangkok Date: 08/04/2016 04:00:00
Could anyone please tell me the correct way to convert data/time using java?
And Could anyone please tell me what I did wrong and why the result is inaccurate?
Your Java have wrong timezone offset: "offset=14400000" is 4 hours, but Moscow is UTC+3 for last year and a half.
Upgrade your java with tzupdater.
Java is using its own timezone data which is independenct from the host operation system. It might be inaccurate if you are not using the latest version of Java cause Russia (Europe/Moscow) has switched from daylight saving time to permanent standard time two years ago
This is one way to do it using your local time zone first.
public static void main(String[] args) {
// Create a calendar object and set it time based on the local time zone
Calendar localTime = Calendar.getInstance();
localTime.set(Calendar.HOUR, 17);
localTime.set(Calendar.MINUTE, 15);
localTime.set(Calendar.SECOND, 20);
int hour = localTime.get(Calendar.HOUR);
int minute = localTime.get(Calendar.MINUTE);
int second = localTime.get(Calendar.SECOND);
// Print the local time
System.out.printf("Local time : %02d:%02d:%02d\n", hour, minute, second);
// Create a calendar object for representing a Bangkok time zone. Then we set
//the time of the calendar with the value of the local time
Calendar BangkokTime = new GregorianCalendar(TimeZone.getTimeZone("Asia/Bangkok"));
BangkokTime.setTimeInMillis(localTime.getTimeInMillis());
hour = BangkokTime.get(Calendar.HOUR);
minute = BangkokTime.get(Calendar.MINUTE);
second = BangkokTime.get(Calendar.SECOND);
// Print the local time in Bangkok time zone
System.out.printf("Bangkok time: %02d:%02d:%02d\n", hour, minute, second);
//Then do the same for the Moscow time zone
Calendar MoscowTime = new GregorianCalendar(TimeZone.getTimeZone("Europe/Moscow"));
MoscowTime.setTimeInMillis(localTime.getTimeInMillis());
hour = MoscowTime.get(Calendar.HOUR);
minute = MoscowTime.get(Calendar.MINUTE);
second = MoscowTime.get(Calendar.SECOND);
// Print the local time in Moscow time zone
System.out.printf("Moscow time: %02d:%02d:%02d\n", hour, minute, second);
}

Covert date time from one zone to another

This is continuation to one of my previous question where I am not able to parse the date which is resolved now. In the below code, I have a date string and I know the time zone for the date string even though the string itself doesn't contain it. Then I need to convert the date into EST time zone.
String clientTimeZone = "CST6CDT";
String value = "Dec 29 2014 11:36PM";
value=StringUtils.replace(value, " ", " ");
DateTimeFormatter df = DateTimeFormat.forPattern("MMM dd yyyy hh:mma").withZone(DateTimeZone.forID(clientTimeZone));
DateTime temp = df.parseDateTime(value);
System.out.println(temp.getZone().getID());
Timestamp ts1 = new Timestamp(temp.getMillis());
DateTime date = temp.withZoneRetainFields(DateTimeZone.forID("EST"));//withZone(DateTimeZone.forID("EST"));
Timestamp ts = new Timestamp(date.getMillis());
System.out.println(ts1+"="+ts);
When I am running the code I am expecting ts1 to remain same and ts to be up by 1 hr. But iam getting below which I don't understand. I thought EST is one hour ahead of CST and so if it is 11 in CST, it should be 12 in EST. Also there seems to be offset by about eleven and half hours. Any clues on what I am missing.
2014-12-30 11:06:00.0=2014-12-30 10:06:00.0
I think the below code will help you.
String clientTimeZone = "CST6CDT";
String toStimeZone = "EST";
String value = "Dec 29 2014 11:36PM";
TimeZone fromTimeZone = TimeZone.getTimeZone(clientTimeZone);
TimeZone toTimeZone = TimeZone.getTimeZone(toStimeZone);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(fromTimeZone);
SimpleDateFormat sf = new SimpleDateFormat("MMM dd yyyy KK:mma");
Date date = sf.parse(value);
calendar.setTime(date);
System.out.println(date);
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
if (fromTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}
calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
if (toTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}
System.out.println(calendar.getTime());
Copied from : http://singztechmusings.wordpress.com/2011/06/23/java-timezone-correctionconversion-with-daylight-savings-time-settings/
The method withZoneRetainFields() preserves the fields in the timezone CST (= UTC-06) hence your local timestamp (as LocalDateTime) but combines it with a different timezone (EST = UTC-05) which is one hour ahead in offset and result in a different instant. You should it interprete it this way: The same local time happens one hour earlier in New York compared to Chicago.
The rule is to subtract positive offsets and to add negative offsets in order to make timestamp representations of instants comparable (normalizing to UTC offset).
Alternatively: Maybe you don't want this but want to preserve the instant instead of the local fields. In this case you have to use the method withZone().
Side notice: Effectively, you compare the instants represented by the variables temp and date and finally use your default timezone to print these instants in the JDBC-escape-format (explanation - you implicitly use Timestamp.toString()). I would rather recommend to use a dedicated instant formatter for this purpose or simpler (to have the offsets in focus):
System.out.println(temp.toInstant() + " = " + date.toInstant());

Date to string is not correnct

Probably there will be simply and fast answer but I still cant find out why is the result of
Date date = new Date(60000); //one min.
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String dateStr = dateFormat.format(date);
dateStr - 01:01:00
Still one hour more. Time zone? How can I set it without it? Thanks.
Date represents a specific moment in time, not a duration. new Date(60000) does not create "one minute". See the docs for that constructor:
Initializes this Date instance using the specified millisecond value. The value is the number of milliseconds since Jan. 1, 1970 GMT.
If you want "one minute from now" you'll probably want to use the Calendar class instead, specifically the add method.
Update:
DateUtils has some useful methods that you might find useful. If you want the elapsed time in HH:mm:ss format, you might try DateUtils.formatElapsedTime. Something like:
String dateStr = DateUtils.formatElapsedTime(60);
Note that the 60 is in seconds.
Three ways to use java.util.Date to specify one minute:
1. Using SimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")) as shahtapa said:
Date date = new Date(60*1000); //one min.
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateStr = dateFormat.format(date);
System.out.println("Result = " + dateStr); //Result should be 00:01:00
2. Using java.util.Calendar as kabuko said:
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.MINUTE,1); //one min.
Date date = calendar.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String dateStr = dateFormat.format(date);
System.out.println("Result = " + dateStr); //Result should be 00:01:00
Other calendar.set() statements can also be used:
calendar.set(Calendar.MILLISECOND,60*1000); //one min.
calendar.set(1970,0,1,0,1,0); //one min.
3. Using these setTimeZone and Calendar ideas and forcing Calendar to
UTC Time-Zone
as Simon Nickerson said:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
calendar.set(Calendar.MINUTE,1); //one min.
Date date = calendar.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateStr = dateFormat.format(date);
System.out.println("Result = " + dateStr); //Result should be 00:01:00
Note: I had a similar issue: Date 1970-01-01 was in my case -3 600 000 milliseconds (1 hour late) java.util.Date(70,0,1).getTime() -> -3600000
I recommend to use TimeUnit
"A TimeUnit represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units. A TimeUnit does not maintain time information, but only helps organize and use time representations that may be maintained separately across various contexts. A nanosecond is defined as one thousandth of a microsecond, a microsecond as one thousandth of a millisecond, a millisecond as one thousandth of a second, a minute as sixty seconds, an hour as sixty minutes, and a day as twenty four hours."
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/TimeUnit.html
Date date = new Date(); // getting actual date
date = new Date (d.getTime() + TimeUnit.MINUTES.toMillis(1)); // adding one minute to the date

How to get the current date and time of your timezone in Java?

I have my app hosted in a London Server. I am in Madrid, Spain. So the timezone is -2 hours.
How can I obtain the current date / time with my time zone.
Date curr_date = new Date(System.currentTimeMillis());
e.g.
Date curr_date = new Date(System.currentTimeMillis("MAD_TIMEZONE"));
With Joda-Time
DateTimeZone zone = DateTimeZone.forID("Europe/Madrid");
DateTime dt = new DateTime(zone);
int day = dt.getDayOfMonth();
int year = dt.getYear();
int month = dt.getMonthOfYear();
int hours = dt.getHourOfDay();
int minutes = dt.getMinuteOfHour();
Date is always UTC-based... or time-zone neutral, depending on how you want to view it. A Date only represents a point in time; it is independent of time zone, just a number of milliseconds since the Unix epoch. There's no notion of a "local instance of Date." Use Date in conjunction with Calendar and/or TimeZone.getDefault() to use a "local" time zone. Use TimeZone.getTimeZone("Europe/Madrid") to get the Madrid time zone.
... or use Joda Time, which tends to make the whole thing clearer, IMO. In Joda Time you'd use a DateTime value, which is an instant in time in a particular calendar system and time zone.
In Java 8 you'd use java.time.ZonedDateTime, which is the Java 8 equivalent of Joda Time's DateTime.
As Jon Skeet already said, java.util.Date does not have a time zone. A Date object represents a number of milliseconds since January 1, 1970, 12:00 AM, UTC. It does not contain time zone information.
When you format a Date object into a string, for example by using SimpleDateFormat, then you can set the time zone on the DateFormat object to let it know in which time zone you want to display the date and time:
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Use Madrid's time zone to format the date in
df.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
System.out.println("Date and time in Madrid: " + df.format(date));
If you want the local time zone of the computer that your program is running on, use:
df.setTimeZone(TimeZone.getDefault());
using Calendar is simple:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Madrid"));
Date currentDate = calendar.getTime();
With the java.time classes built into Java 8 and later:
public static void main(String[] args) {
LocalDateTime localNow = LocalDateTime.now(TimeZone.getTimeZone("Europe/Madrid").toZoneId());
System.out.println(localNow);
// Prints current time of given zone without zone information : 2016-04-28T15:41:17.611
ZonedDateTime zoneNow = ZonedDateTime.now(TimeZone.getTimeZone("Europe/Madrid").toZoneId());
System.out.println(zoneNow);
// Prints current time of given zone with zone information : 2016-04-28T15:41:17.627+02:00[Europe/Madrid]
}
You would use JodaTime for that. Java.util.Date is very limited regarding TimeZone.
Check this may be helpful. Works fine for me. Code also covered daylight savings
TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
Calendar cal = Calendar.getInstance();
// If needed in hours rather than milliseconds
int LocalOffSethrs = (int) ((cal.getTimeZone().getRawOffset()) *(2.77777778 /10000000));
int ChinaOffSethrs = (int) ((tz.getRawOffset()) *(2.77777778 /10000000));
int dts = cal.getTimeZone().getDSTSavings();
System.out.println("Local Time Zone : " + cal.getTimeZone().getDisplayName());
System.out.println("Local Day Light Time Saving : " + dts);
System.out.println("China Time : " + tz.getRawOffset());
System.out.println("Local Offset Time from GMT: " + LocalOffSethrs);
System.out.println("China Offset Time from GMT: " + ChinaOffSethrs);
// Adjust to GMT
cal.add(Calendar.MILLISECOND,-(cal.getTimeZone().getRawOffset()));
// Adjust to Daylight Savings
cal.add(Calendar.MILLISECOND, - cal.getTimeZone().getDSTSavings());
// Adjust to Offset
cal.add(Calendar.MILLISECOND, tz.getRawOffset());
Date dt = new Date(cal.getTimeInMillis());
System.out.println("After adjusting offset Acctual China Time :" + dt);
I couldn't get it to work using Calendar. You have to use DateFormat
//Wednesday, July 20, 2011 3:54:44 PM PDT
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateTimeString = df.format(new Date());
//Wednesday, July 20, 2011
df = DateFormat.getDateInstance(DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateString = df.format(new Date());
//3:54:44 PM PDT
df = DateFormat.getTimeInstance(DateFormat.FULL);
df.setTimeZone(Timezone.getTimeZone("PST"));
final String timeString = df.format(new Date());
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API: If you want to get just date and time (and not the timezone information), you can use LocalDateTime.#now(ZoneId).
The non-parametrized overloaded, LocalDateTime.#now returns the current Date-Time using the JVM's timezone. It is equivalent to using LocalDateTime.now(ZoneId.systemDefault()).
Demo:
import java.time.LocalDateTime;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now(ZoneId.of("Europe/Madrid"));
System.out.println(now);
}
}
Output from a sample run:
2021-07-25T15:54:31.574424
ONLINE DEMO
If you want to get the date and time along with the timezone information, you can use ZonedDateTime.#now(ZoneId). It's non-parametrized variant behave in the same manner as described above.
Demo:
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Madrid"));
System.out.println(now);
}
}
Output from a sample run:
2021-07-25T16:08:54.741773+02:00[Europe/Madrid]
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and 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.
You can try ZonedDateTime.now() . You can find it in package java.time
import java.time.ZonedDateTime;
public class Temp {
public static void main(String args[]) {
System.out.println(ZonedDateTime.now(ZoneId.of("Europe/Madrid")));
}
}
Output (I'm based in kolkata,India):
2021-09-17T14:46:14.341+02:00[Europe/Madrid]
To get date and time of your zone.
Date date = new Date();
DateFormat df = new SimpleDateFormat("MM/dd/YYYY HH:mm a");
df.setTimeZone(TimeZone.getDefault());
df.format(date);
To get the date to a variable .
public static String getCurrentDate(){
final ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));
String Temporal= DateTimeFormatter.ofPattern("yyyy-MM-dd").format(now);
String today= LocalDate.now().format(DateTimeFormatter.ofPattern(Temporal));
return today;
}
Here are some steps for finding Time for your zone:
Date now = new Date();
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("Europe/London"));
System.out.println("timeZone.......-->>>>>>"+df.format(now));
Date in 24 hrs format
Output:14/02/2020 19:56:49 PM
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss aa");
dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
System.out.println("date is: "+dateFormat.format(date));
Date in 12 hrs format
Output:14/02/2020 07:57:11 PM
Date date = new Date();`enter code here`
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa");
dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
System.out.println("date is: "+dateFormat.format(date));
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateTimeString = df.format(new Date());

Categories

Resources