in java, equivalent to date(String) method? - java

I want to get the difference between two times. I.e., current time and time1 (like "17 Jun 2011 01:59:25"). By one way, we can do by using Date(string). But it is deprecated method. How to do this with a non-deprecated method?

Use java.text.SimpleDateFormat to parse a string into a Date object. For example:
String text = "17 Jun 2011 01:59:25";
DateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
Date date = df.parse(text);
You can get the time difference between two Date objects by calling getTime() on them and subtracting the values:
Date now = new Date();
long diff = now.getTime() - date.getTime();
System.out.println("Time difference in milliseconds: " + diff);
If you want to know the difference in seconds, minutes, hours, etc. then divide the number of milliseconds by the appropriate factor.

There is comment on deprecated tag
replaced by DateFormat.parse(String s)

Related

How to convert two different strings to date format and finding their differences in JSP/JAVA

I have 2 strings
Str1: 2016-7-25.15.38. 32. 0 (This is what im getting from DB)
String2 : July 25, 2016 3:19 PM (This one I wrote a program to read from the email timestamp)
How to convert these 2 strings to date format and find their differnce in time.. Pls help.
Ive gone through so many pages in SO and google but not getting anything specific
How to convert these 2 strings to date format
Using Java 8, you'd parse them like this:
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime dt1 = ZonedDateTime.parse("2016-7-25.15.38. 32. 0",
DateTimeFormatter.ofPattern("uuuu-M-d.H.m. s. 0").withZone(zoneId));
ZonedDateTime dt2 = ZonedDateTime.parse("July 25, 2016 3:19 PM",
DateTimeFormatter.ofPattern("MMMM d, uuuu h:mm a").withZone(zoneId));
Using a non-standard indentation to align format string with value to be parsed, for easier comparison.
The code is using ZonedDateTime so Daylight Savings Time will be handled correctly.
and find their difference in time
Getting the difference in time is then easy enough, using until() or between():
long seconds = dt1.until(dt2, ChronoUnit.SECONDS);
long seconds = ChronoUnit.SECONDS.between(dt1, dt2);
They are the same. Use whichever you like best.
If you print the values above, you get (I'm in USA Eastern time zone):
2016-07-25T15:38:32-04:00[America/New_York]
2016-07-25T15:19-04:00[America/New_York]
-1172
I would simply use Oracle to figure out the difference. It's quite easy:
select to_date('2016-07-25.15.38.32', 'yyyy-mm-dd.hh24.mi.ss') - to_date('July 25, 2016 3:19 PM', 'Month dd, yyyy hh:mi PM')
from dual
1.Convert java.sql.timestamp into java.util.Date
Date startDate = new Date(startTimestamp.getTime());
Date endDate= new Date(endTimestamp.getTime());
2.You can find the time difference using TimeUnit enum as below.
Date startDate = // Set start date
Date endDate = // Set end date
long duration = endDate.getTime() - startDate.getTime();
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
and so on..

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 convert Standard Date into minutes in java?

How to convert standard output of date into number of minutes?
I have output from my command as:
Mon Mar 4 12:33:58 2013
and I need to convert it into number of minutes say minutes1.
because I have a code which gives number of minutes for current time and the code is:
public class DateToMinutes {
public static void main(String[] args) {
Date date = new Date();
long now = ((date.getTime()) / (60000));
System.out.println("Total Minutes are " + now);
}
}
the output of this will be in minutes say minutes2.
I need to compare both minutes1 and minutes2.
since I am unable to convert Standard date into minutes1, it's not possible right now.
look at parse method of SimpleDateFormat, there you'll find formats used for converting dates.
Javadocs here
In your case something like this should work:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy");
Date theDate = sdf.parse ("Mon Mar 4 12:33:58 2013");
long minutes2 = theDate.getTime() / 60000;
Use a simpledate formatter.
DateFormat formatter = new SimpleDateFormat("mm");
Date one = ...
Date two = ...
formatter.format( one) ); // only the minutes remain
formatter.format( two) ); // only the minutes remain
// do whatever you want.
Determining minutes1 is parsing a date and transforming it.
Related issues can be found here and here.
This should do the job based on your description of the date format:
SimpleDateFormat yourStandardDateFormat = new SimpleDateFormat("EEE MMM dd kk:mm:ss yyyy");
Date date = yourStandardDateFormat.parse( stringRepresentingDate );
long minutes1 = date.getTime() / 60000l;
For reference, see SimpleDateFormat documentation

How to compare dates using Java [duplicate]

This question already has answers here:
How to compare dates in Java? [duplicate]
(11 answers)
Closed 6 years ago.
I have a date with the format 2012-02-02(yyyy-MM-dd).
For example if todays date is 2012-02-02 i need to add one and a half days to it which would make it 2012-02-03 06:00:00.0.
And if i have a number of dates of the following format 2012-02-03 06:30:00.0(yyyy-MM-dd HH:MM:SS.SSS) , i need to compare if all these dates are less than,greater than or equal to the date to which one and a half days were added above.
The comparison should also take care of the hours while comparing if the dates are less than,greater than or equal or equal to the other date and time.
How do i achieve the same.
Simple arithmetic approach (faster)
Parse the date using SimpleDateFormat that creates a Date object
Use Date.getTime() to return the UTC value in long
Convert 1 and half days to millis (1.5 Days = 129600000 Milliseconds) and add it to previous step
Use >, < and == or after(), before() and equals() if you want to use Date object itself
API approach (slower)
Use Calendar
add(...) method for adding 1 and half day
use before(), after() and equals() methods of Calendar
well so i hope this will give you a clear idea. Calendar Documentation and SimpleDateFormat Documentaion
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String aDateString = "2012-02-02";
Date date = sdf.parse(aDateString);
System.out.println("reference date:"+date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, 36);
System.out.println("added one and half days to reference date: "+cal.getTime());
String newDateString = "2012-02-03 06:30:00.0";
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date newDate = sdf.parse(newDateString);
System.out.println("new date to compare with reference date : "+newDate);
Calendar newCal = Calendar.getInstance();
newCal.setTime(newDate);
if(cal.after(newCal)){
System.out.println("date is greater than reference that.");
}else if(cal.before(newCal)){
System.out.println("date is lesser than reference that.");
}else{
System.out.println("date is equal to reference that.");
}
OUTPUT :
reference date:Thu Feb 02 00:00:00 IST 2012
added one and half days to reference date: Fri Feb 03 12:00:00 IST 2012
new date to compare with reference date : Fri Feb 03 06:30:00 IST 2012
date is greater than reference that.
Use SimpleDateFormat to convert String to Date
Set date to Calendar instance
use calendar.add(Calendar.HOUR, 36)
Also See
Joda Time API
You need to use Joda date time API.
String strDate="2012-02-02";
DateTime dateTime=DateTime.parse(strDate);
DateTime newDateTime=dateTime.plusHours(18);
System.out.println(dateTime);
System.out.println(newDateTime);

Categories

Resources