Java date string parse creates difference of timezone - java

I am bit frustrated by this.
I have a String "2015-02-18T23:44:59" which represents time in GMT format.
I want to parse this date into date object.
String dateStr = "2015-02-18T23:44:59";
Date date = DateUtils.parseDate(dateStr, new String[]{"yyyy-MM-dd'T'HH:mm:ss"});
System.out.println(dateStr + " \t" + date.toString());
This outputs :
2015-02-18T23:44:59 Thu Feb 19 05:14:59 IST 2015
As you can see latter time has time zone IST but my original time was GMT.
I don't think there is any parse function which takes current date's time zone.
One way to answer is this question is that :
date.setTime(date.getTime() + ( date.getTimezoneOffset() * 60 * 1000));
System.out.println("\t" + date.toString());
This outputs:
Wed Feb 18 23:44:59 IST 2015
Which seems correct time (but incorrect time zone). Additionally, getTimezoneOffset() is deprecated.
Can anyone suggest me a better way to deal with String dates considering time zones.

I'd use a date format:
SimpleDateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = utcFormat.parse("2015-02-18T23:44:59");

Related

How to calculate next week?

I want to precisely calculate the time one week from a given date, but the output I get back is one hour early.
code:
long DURATION = 7 * 24 * 60 * 60 * 1000;
System.out.println(" now: " + new Date(System.currentTimeMillis()));
System.out.println("next week: " + new Date(System.currentTimeMillis() + DURATION));
output:
now: Wed Sep 16 09:52:36 IRDT 2015
next week: Wed Sep 23 08:52:36 IRST 2015
How can I calculate this correctly?
Never, ever rely on millisecond arithmetic, there are too many rules and gotchas to make it of any worth (even over a small span of time), instead use a dedicated library, like Java 8's Time API, JodaTime or even Calendar
Java 8
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = now.plusDays(7);
System.out.println(now);
System.out.println(then);
Which outputs
2015-09-16T15:34:14.771
2015-09-23T15:34:14.771
JodaTime
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = now.plusDays(7);
System.out.println(now);
System.out.println(then);
Which outputs
2015-09-16T15:35:19.954
2015-09-23T15:35:19.954
Calendar
When you can't use Java 8 or JodaTime
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DATE, 7);
Date then = cal.getTime();
System.out.println(now);
System.out.println(then);
Which outputs
Wed Sep 16 15:36:39 EST 2015
Wed Sep 23 15:36:39 EST 2015
nb: The "problem" you seem to be having, isn't a problem at all, but simply the fact that over the period, your time zone seems to have entered/exited day light savings, so Date is displaying the time, with it's correct offset
Try this
Calendar cal = Calendar.getInstance();
System.out.println(cal.getTime());
cal.add(Calendar.DAY_OF_MONTH, 7);
System.out.println(cal.getTime());
The difference is because of the different timezone. IRDT is +0430 and IRST is +0330
To overcome this issue you can use the JodaTime.
LocalDateTime now = LocalDateTime.now();
LocalDateTime nextweek = now.plusDays(7);
System.out.println(now);
System.out.println(nextweek);
As other said. It would be better to use Calendar or JodaTime library. But the question is why you were not getting the desired result. It was because currentTimeMillis() calculates time between "computer time" and coordinated universal time (UTC). Now consider following case.
long DURATION = 7 * 24 * 60 * 60 * 1000;
Date now = new Date();
Date nextWeek = new Date(now.getTime() + DURATION);
System.out.println(" now: " + now);
System.out.println("next week: " + nextWeek);
here Date.getTime() calculate time from 00:00:00 GMT every time and then when converted to string will give time for your local time zone.
Edit :
I was wrong. The reason is as simon said.
The actual "why" is that IRDT (Iran Daylight Time) ends on September
22nd. That's why the first date (September 16th) in the OP's post is
displayed as IRDT and the second date (September 23rd) is displayed as
IRST. Because IRST (Iran Standard Time) is one hour earlier than IRDT
the time displayed is 08:52:36 instead of 09:52:36.

How to get selected month last date last timestamp in java?

From the below java code I'm getting a month First & last dateTimestamp, but here i need last dateTimestamp as - "Mon Aug 31 23:59:59 IST 2015" instead of - "Mon Aug 31 00:00:00 IST 2015"?
Calendar cal = Calendar.getInstance();
int year = 2015;
int month = 07;
cal.set(cal.DATE,1);
cal.set(cal.YEAR,year);
cal.set(cal.MONTH, month);
String firstDate = (cal.getActualMinimum(cal.DATE) + "/" + (month+1) + "/" +year);
System.out.println("firstDate-->"+"\t"+firstDate);
String lastDate = (cal.getActualMaximum(cal.DATE) + "/" + (month+1) + "/" +year);
System.out.println("lastDate-->"+"\t"+lastDate);
DateFormat firstFormat = new SimpleDateFormat("dd/MM/yyyy");
Date beginDate = firstFormat.parse(firstDate);
System.out.println("BeginDate Timestamp"+ "\t" + beginDate);
DateFormat secoundFormat = new SimpleDateFormat("dd/MM/yyyy");
Date endDate = secoundFormat.parse(lastDate);
System.out.println("endDate Timestamp"+ "\t" + endDate);
Output:->
firstDate--> 1/8/2015
lastDate--> 31/8/2015
BeginDate Timestamp Sat Aug 01 00:00:00 IST 2015
endDate Timestamp Mon Aug 31 00:00:00 IST 2015
Please help me if we have any solution.
If I understand your question, it looks as if you want to pass a year and month into a method, and get back the last day of the passed month.
I would suggest consider (in this order):
which jdk you use
configuration of calendar
configuration of timezone (maybe)
using jodatime
As of 1.8 many JodaTime-like features have been added to the jdk- e.g. see https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html (If you arent using 1.8 you can use the joda lib, assuming your organization allows it)
Calendar.getInstance() gives a default TimeZone and a default Locale, which means the definitions of the running JVM. You may or may not need to consider this and implement more than just getInstance(). See API javadoc.
Assuming a Gregeorian Calendar (hey, you could be Bahaian and have 19 months in the year ...) , here is one partial implementation using JDK 1.7, JodaTime jar 2.2, validation-1.0.0.GA jar:
#Test
public void testDate() {
final String dateStringOfFirstDay = "1.7.2015";
final Date lastDayOfMonth = getLastDayOfMonth(dateStringOfFirstDay);
Assert.assertNotNull(lastDayOfMonth);
//more assertions ...
}
private Date getLastDayOfMonth(#NotNull String dateStringOfFirstDay) {
//further validation here necessary according to required date format
DateTime dt = DateTime.parse(dateStringOfFirstDay);
return dt.dayOfMonth().withMaximumValue().toDate();
}
The defintion of DateFormat/DateTimeFormat and further result assertions is left up to you.
Best of luck!
Guys I got a solution for my question!!!
I think it will help u too...
Calendar calendar = Calendar.getInstance();
int year=2015;
int month=7;
int date=31;
int hourOfDay=23;
int minute=59;
int second=59;
int milliSecond=999;
calendar.set(year, month, date, hourOfDay, minute, second);
calendar.set(calendar.MILLISECOND, milliSecond);
System.out.println("Time from Calendar: "+calendar.getTime());
long timeInMilliSeconds=calendar.getTimeInMillis();
System.out.println("timeInMilliSeconds from calendar: "+timeInMilliSeconds);
Timestamp timestamp=new Timestamp(timeInMilliSeconds);
System.out.println(timestamp);
The above program gives the last date last timestamp in a selected month.
getTimeInMillis() takes the time from Jan 01, 1970 to current time in Milliseconds.
Using those milliseconds i'm getting the Timestamp.
Thank you for your help guys!!!
OutPut:->
Time from Calendar: Mon Aug 31 23:59:59 IST 2015
timeInMilliSeconds from calendar: 1441045799999
2015-08-31 23:59:59.999

Convert UTC Date to local Date

I am converting from epoch time (which is in UTC) to a format as shown below. Now I tried different SO answers to convert UTCDate from UTC to local time. But I am not getting the local time.
Any help would be appreciated.
String epochTime = "1436831775043";
Date UTCDate = new Date(Long.parseLong(epochTime));
Date localDate; // How to get this?
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
String result = simpleDateFormat.format(UTCDate);
Also, the conversion has to be done without the help of any external library.
Java 8
String epochTime = "1436831775043";
Instant utcInstant = new Date(Long.parseLong(epochTime)).toInstant();
ZonedDateTime there = ZonedDateTime.ofInstant(utcInstant, ZoneId.of("UTC"));
System.out.println(utcInstant);
LocalDateTime here = there.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
System.out.println(here);
Which outputs:
2015-07-13T23:56:15.043Z
2015-07-14T09:56:15.043
After thoughts...
I think you're chasing your tail. Date is just a container for the number of milliseconds since the epoch (January 1, 1970, 00:00:00 GMT). It doesn't internally carry a representation of a time zone (AFAIK).
For example...
String epochTime = "1436831775043";
Date UTCDate = new Date(Long.parseLong(epochTime));
// Prints the "representation" of the Date
System.out.println(UTCDate);
// Local date/time format...
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy h:mm:ss a");
try {
System.out.println("local format: " + simpleDateFormat.format(UTCDate));
System.out.println("local Date: " + simpleDateFormat.parse(simpleDateFormat.format(UTCDate)));
} catch (ParseException ex) {
Logger.getLogger(JavaApplication203.class.getName()).log(Level.SEVERE, null, ex);
}
// UTC date/time format
try {
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("utc format: " + simpleDateFormat.format(UTCDate));
System.out.println("utc date: " + simpleDateFormat.parse(simpleDateFormat.format(UTCDate)));
} catch (ParseException ex) {
Logger.getLogger(JavaApplication203.class.getName()).log(Level.SEVERE, null, ex);
}
Which outputs...
Tue Jul 14 09:56:15 EST 2015
local format: 14/07/2015 9:56:15 AM
local Date: Tue Jul 14 09:56:15 EST 2015
utc format: 13/07/2015 11:56:15 PM
utc date: Tue Jul 14 09:56:15 EST 2015
If you have a look at local Date and utc date they are the same thing, even though the local format and utc format are formatted correctly.
So, instead of chasing your tale trying to get Date to "represent" a value you want, either use Java 8's Time API or JodaTime to manage the Time Zone information or simply format the Date into the Time Zone you want...
Further, if we do something like...
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy h:mm:ss a");
Date localDate = simpleDateFormat.parse(simpleDateFormat.format(UTCDate));
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date utcDate = simpleDateFormat.parse(simpleDateFormat.format(UTCDate));
System.out.println(localDate.getTime());
System.out.println(utcDate.getTime());
System.out.println(localDate.equals(utcDate));
It will print...
1436831775000
1436831775000
true
You can set your time zone in the formatter:
simpleDateFormat.setTimeZone(TimeZone.getDefault());

Parsing time stamp strings from a different time zone

I have a String with timestamp in GMT. I want to convert this to a DateTime object in EST.
E.g If the string has:
final String gmtTime = "20140917-18:55:25"; // 4:55 PM GMT
I need to convert this to : 20140917-12:55:25 //12:55 PM EST
All these tries failed:
System.out.println("Time in GMT " + DateTimeFormat.forPattern("yyyyMMdd-HH:mm:ss").parseDateTime(gmtTime));
System.out.println("Time in EST " +
DateTimeFormat.forPattern("yyyyMMdd-HH:mm:ss").parseDateTime(gmtTime).withZone(DateTimeZone.forID("America/New_York")));
Output:
Time in GMT 2014-09-17T18:55:25.000-04:00
Time in EST 2014-09-17T18:55:25.000-04:00 //I expect: 2014-09-17T12:55:25.000-04:00
Any suggestions?
Joda-Time
Here a Joda-Time 2.4 solution:
String gmtTime = "20140917-18:55:25";
DateTime dateTimeGMT =
DateTimeFormat.forPattern("yyyyMMdd-HH:mm:ss").withZoneUTC().parseDateTime(gmtTime);
System.out.println("Time in GMT " + dateTimeGMT); // Time in GMT 2014-09-17T18:55:25.000Z
System.out.println(
"Time in EST "
+ DateTimeFormat.forPattern("yyyyMMdd-HH:mm:ss").withZone(
DateTimeZone.forID("America/New_York")
).print(dateTimeGMT)
); //Time in EST 20140917-14:55:25
I think that you have the wrong expectation regarding the result. EST (more correct to use is "America/New_York" as zone identifier) is four hours behind UTC, hence the local timestamp there is four hours earlier than the local representation of the same moment at UTC-offset.
Also note that I set the timezone on the formatter not on the parsed DateTime-object.
#Test
public void TimeZoneTest() {
Date now = new Date();
String DATE_PATTERN = "yyyyMMdd-HH:mm:ss";
DateFormat dfEST = new SimpleDateFormat(DATE_PATTERN);
dfEST.setTimeZone(TimeZone.getTimeZone("America/New_York"));
DateFormat dfGMT = new SimpleDateFormat(DATE_PATTERN);
dfGMT.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dfEST.format(now));
System.out.println(dfGMT.format(now));
}
And the output is:
20140919-09:02:19
20140919-13:02:19

Get correct long value from parsed Date (Timezone issue)

I'm trying to parse a date from a String and get the long value. The long value will be later sent to an SQL query.
here's my code:
String dayDate = "28-02-2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date day = new Date();
try {
day = sdf.parse(dayDate);
} catch (ParseException pe) {
pe.printStackTrace();
}
System.out.println("day : "+day.toString()+ " long : " + day.getTime());
which gives the following output:
day : Thu Feb 28 00:00:00 EET 2013 long : 1362002400000
which is correct but not what I want since the long value results in Wed, 27 Feb 2013 22:00:00 GMT (http://www.epochconverter.com/) (I'm in a GMT+2 timezone). And i need to send to correct long value to sql.
Is there anyway to work around this without using external libraries?
SimpleDateFormat is locale-aware, meaning the date it parses is in your timezone. Midnight 28 Feb in GMT+2 is actually 10pm 27 Feb in GMT, the long value 1362002400000. I would add this to get the parsing right (would't bother using Calendar):
sdf.setTimeZone(TimeZone.getTimeZone("GMT"))
Again, when you print this date it uses SimpleDateFormat and that's why you can see EET in the output.
Passing this to database is a different story though once you get this right.
Use DateFormat.setCalendar(Calendar cal) to set a Calendar with GMT as its timezone, or use DateFormat.setTimeZone(TimeZone zone) with the GMT TimeZone. That will ensure that the resulting Date will be 00:00:00 in GMT instead of in EET.
If you add a timezone specifier to your string you can force java to use GMT for the conversion:
String dayDate = "28-02-2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy z"); // z is a timezone specifier
Date day = new Date();
try {
day = sdf.parse(dayDate + " GMT"); // Use GMT timezone.
} catch (ParseException pe) {
pe.printStackTrace();
}
System.out.println("day : "+day.toString()+ " long : " + day.getTime());
You are converting between text and internal (Date) representations of dates and times without explicitly stating the time-zone. That never goes well.
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
Date date = calendar.getTime();
Use your timezone String:
TimeZones

Categories