GWT - Displayed date is decremented one day - java

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

Related

SimpleDateFormat sets current day for parsed date

Is there any way to use the following simpleDateFormat:
final SimpleDateFormat simpleDateFormatHour = new SimpleDateFormat("HH:mm:ss z");
and when invoking:
simpleDateFormat.parse("12:32:21 JST");
to return current date on the Date object?
For these example, it will return:
Thu Jan 01 05:32:21 EET 1970
and not:
<<today>> 05:32:21 EET <<currentYear>>
as I need.
No, SimpleDateFormat needs explicity the date in the input string. If you're using Java 8, you can go with a LocalDateTime:
LocalDateTime localDateTime = LocalDate.now().atTime(5, 32, 21);
If you want to include a time-zone, you can use ZonedDateTime.
Construct another SimpleDateFormat to print today's date:
String today = new SimpleDateFormat("yyyy/MM/dd").print(new Date());
(Be careful here: you might want to set the time zone on the SimpleDateFormat, as "today" is different in different time zones).
Update the date format to include year, month and day:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z");
And then prepend the date string with the date you want:
simpleDateFormat.parse(today + " " + "12:32:21 JST");
A better solution using flexible default values (today instead of 1970-01-01) would be in Java-8 with the new built-in date-time-library located in package java.time:
String input = "12:32:21 JST";
String pattern = "HH:mm:ss z";
LocalDate today = LocalDate.now(ZoneId.of("Asia/Tokyo"));
DateTimeFormatter dtf =
new DateTimeFormatterBuilder().parseDefaulting(ChronoField.YEAR, today.getYear())
.parseDefaulting(ChronoField.MONTH_OF_YEAR, today.getMonthValue()).parseDefaulting(
ChronoField.DAY_OF_MONTH,
today.getDayOfMonth()
).appendPattern(pattern).toFormatter(Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(input, dtf);
System.out.println(zdt); // 2016-12-23T12:32:21+09:00[Asia/Tokyo]
However, I still see a small bug related to the fact that this code makes a hardwired assumption about the used zone BEFORE parsing the real zone so please handle with care. Keep in mind that the current date depends on the zone. But maybe you only need to handle a scenario where just the Japan time is used by users.
Hint: You can also parse in two steps. First step with any kind of fixed default date in order to get the zone information of the text to be parsed. And then you can use this zone information for suggested solution above. An awkward but safe procedure.
You can use this code if you want to change only the year and the day
final SimpleDateFormat simpleDateFormatHour = new SimpleDateFormat("HH:mm:ss z");
Date date = simpleDateFormatHour.parse("12:32:21 JST");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR));
calendar.set(Calendar.DAY_OF_YEAR, Calendar.getInstance().get(Calendar.DAY_OF_YEAR));
date = calendar.getTime();

Java - Not getting the timestamp for a specific timezone

In the below code, i m trying to get dateformat for timezone PST, but i didnt get the expected output.
But, If I uncomment the 2 lines (setDefault timezone), i m getting the expected results.
Do you have any good option?
System.out.println("TimeZone.getDefault():"+TimeZone.getDefault()); // CST
//TimeZone.setDefault(TimeZone.getTimeZone("PST"));
Calendar cal = java.util.Calendar.getInstance(SimpleTimeZone.getTimeZone("PST"));
//Calendar cal = java.util.Calendar.getInstance();
Date c = cal.getTime();
String out = new java.text.SimpleDateFormat("MMMMMddyyyy").format(c);
System.out.println("out:"+out);
If the current date in CST is February082015 (at night 12 to 2 AM), then the expected output for PST would be February072015 (PST is 2hrs behind CST). But, I m getting the output as February082015.
Your DateFormat doesn't inherit a TimeZone from the Calender. To demonstrate, I've added a Z (which will display the time-zone offset). Run it with and without setting the TimeZone and your observed behavior is explained
DateFormat df = new SimpleDateFormat("MMMMMddyyyy Z"); // <-- The Z is TZ
df.setTimeZone(SimpleTimeZone.getTimeZone("PST")); // <-- Add/Remove this
String out = df.format(c);

Getting time in Germany - Android

How can I get the current time in Germany regardless of the location of the user and current device time?
Calendar buttoncal = Calendar.getInstance();
String tdate = new SimpleDateFormat("dd.MM",Locale.GERMANY).format(buttoncal.getTime());
String tday = new SimpleDateFormat("EEEE",Locale.GERMANY).format(buttoncal.getTime());
one_date.setText(tdate.toString());
one_day.setText(tday);
You can specify the timezone that needs to be used:
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("Europe/Berlin"));
For a list of available time zones: TimeZone.getAvailableIDs().
Note: the locale in the SimpleDateFormat is used to read/format strings in that locale - using a German locale, for example, will print the months / days names in German. But it has nothing to do with the time zone.
Try using this:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.GERMANY);
Date date = new Date();
dateFormat.format(date);
You'll get the 'date' in the format "yyyy-MM-dd HH:mm". Then you can use .split() to split the returned string format using space as delimiter. Something like:
String[] str_array = date.toString().split(" ");
String time = str_array[1];
Use android.text.format.Time instead as I suggested over here.

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

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".

Parsing date with different time zones

Even with about 15 years in Java one always stumbles over the topic of handling dates and times...
Here's the situation: I get a timestamp from some external system as a String representation. The timestamp's semantic is that it represents an UTC date. This timestamp has to be put in an entity and then into a PostgreSQL database in a TIMESTAMP field. Additionally I need to put the same timestamp as local time (in my case CEST) into the entity and then into the database in a TIMESTAMP WITH TIME ZONE field.
What is the right way to ensure that no matter what the settings of the machine executing the code are, the timestamps get stored correctly in the entity (to make some validations with other UTC timestamps) and in the database (to use them in reports later on)?
Here's the code, which worked fine on my local machine:
SimpleDateFormat sdfUTC = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
sdfUTC.setTimeZone(TimeZone.getTimeZone("UTC"));
Date utcTimestamp = sdfUTC.parse(utcTimestampString);
// getMachinesTimezone is some internal util method giving the TimeZone object of the machines Location
Calendar localTimestamp = new GregorianCalendar(getMachinesTimezone());
localTimestamp.setTimeInMillis(utcTimestamp.getTime());
But when executing the same code on the server, it resulted in different times, so I assume that it's not the correct way to handle it. Any suggestions?
PS: I read about Joda Time when searching in this forum, but in the given project I'm not able to introduce new libraries since I only change an existing module, so I have to live with the standard JDK1.6
If I understand correctly, You need to set the timezone on the same data/calendar object that you are printing. Like this:
private Locale locale = Locale.US;
private static final String[] tzStrings = {
"America/New_York",
"America/Chicago",
"America/Denver",
"America/Los_Angeles",
};
Date now = new Date();
for ( TimeZone z : zones) {
DateFormat df = new SimpleDateFormat("K:mm a,z", locale);
df.setTimeZone(z);
String result = df.format(now);
System.out.println(result);
}
if i set timezone to SimpleDateFormat it is working fine.
here is the sample code...
String date="05/19/2008 04:30 AM (EST)";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm aaa (z)");
TimeZone.setDefault(TimeZone.getTimeZone("PST"));
long millis = sdf.parse(date).getTime();
sdf.setTimeZone(TimeZone.getDefault());
System.out.println(sdf.format(new Date(millis)));
I think you have to set the target time zone in you Calendar object. I think something like:
Calendar localTimestamp = new GregorianCalendar(TimeZone.getTimeZone("GMT+10"));
localTimestamp.setTimeInMillis(utcTimestamp.getTime());
In other case Java takes the default system time zone for the Calendar instance.
You can do it by the below example code.
Date date = new Date();
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("CET"));
Date date1 = dateformat.parse(formatter.format(date));
// Set the formatter to use a different timezone
formatter.setTimeZone(TimeZone.getTimeZone("IST"));
Date date2 = dateformat.parse(formatter.format(date));
// Prints the date in the IST timezone
// System.out.println(formatter.format(date));

Categories

Resources