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);
Related
I want to be able to request java to get the current date, then I would like to control the time added to that date object and then convert that date object to unix time.
i.e. something like
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
Then do this using the Calendar object as a converted string
String dateString = "Fri, 09 Nov 2012 23:40:18 GMT"; //but this
DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy
hh:mm:ssz");
Date date = dateFormat.parse(dateString );
long unixTime = (long) date.getTime()/1000;
System.out.println(unixTime );
Any help would be appreciated.
First of all, there are some issues with your date format: You have to use capital H for hours when parsing 24-hour times, and I think there was a space missing in front of the timezone z.
Using the newer Java time API, you can try this:
ZonedDateTime.parse("Fri, 09 Nov 2012 23:40:18 GMT", DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z"))
.with(LocalDate.now())
.toEpochSecond();
The new API is very strict when it come to timezones, you might want to watch out for that. In this implementation, the parsed time defines the timezone (GMT in this example). But maybe you want your local timezone (defined by the virtual machine)? In this case, you can turn it around: ZonedDateTime.now().with(ZonedDateTime.parse(...).toLocalTime()).
In your original approach, why do you not continue with the Calendar?
Date parsedDate = ...;
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, parsedDate.getHours());
today.set(Calendar.MINUTE, parsedDate.getMinutes());
today.set(Calendar.SECOND, parsedDate.getSeconds());
today.set(Calendar.MILLISECOND, 0);
long epoch = today.getTimeInMillis() / 1000;
But again, beware of timezones.
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
So from all the posts I read about this issue (for example, Convert timestamp to UTC timezone).
I learn that a way to do this conversion is :
SimpleDateFormat dfmaputo = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a");
dfmaputo.setTimeZone(TimeZone.getTimeZone("UTC"));
long unixtime = dfmaputo.parse(data.get(1)).getTime();
unixtime = unixtime / 1000;
output:
original date (Maputo Timezone) -- 11/5/2015 1:39:45 PM
unix timestamp in UTC --- 1446687585
data.get(1) is the string with the maputo datetime.
I don't understand why I'm not getting the UTC value. When I convert the unix timestamp, that I was expecting to be in UTC, I get the original datetime with Maputo Timezone.
Am I missing something?
Do I need to convert first to my local timezone and than to UTC?
EDIT: Solution
Calendar maputoDateTime = Calendar.getInstance(TimeZone.getTimeZone("Africa/Maputo"));
maputoDateTime.setTimeZone(TimeZone.getTimeZone("GMT"));
Long unixtimeGMT = maputoDateTime.getTimeInMillis() / 1000;
Instead of SimpleDateFormat I should use Calendar.
First I needed to set the input date's timezone (Africa/Maputo) and then set it to the one I needed (GMT). And only then I could get the correct unix timestamp.
Thanks to #BastiM reply in How to change TIMEZONE for a java.util.Calendar/Date
Thank you for your replies and help.
What if you add CAT timezone identifier to the end of string and formatter mask has z letter? If thats what you always get and source data does not give timezone value.
String sdt = "11/5/2015 11:39:45 PM CAT";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a z", Locale.US);
Date dt = sdf.parse(sdt);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(dt.getTime());
System.out.println(dt + ", utc=" + dt.getTime());
System.out.println(cal);
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());
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));