I've the following two dates in a string format and would like to get the elapsed time for those.
Date elapsed = new Date(
new SimpleDateFormat().parse("10/17/2014, 2:19:22 PM").getTime()
- new SimpleDateFormat().parse("10/17/2014, 2:19:32 PM").getTime());
System.out.println("Elapsed Time: " + elapsed);
However, I get ...ParseException: Unparseable date: "10/17/2014, 2:19:22 PM" does anyone know why?
Note: here is how I got the date you see in parse block generated new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time)
You have to specify format in SimpleDateFormat constructor.
Your String has format dd/MM/yyyy, hh:mm:ss a
Your logic of substraction is incorrect as it will give you the long value difference between dates and you are creating date from that value which is not valid.For that you have to get exact difference from that long value.You have to divide diff with (1000 * 60) to get minutes, (1000 * 60 * 60) to get Seconds and (1000 * 60 * 60 * 24) to get days.
SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy, hh:mm:ss a");
long diff = sdf.parse("10/17/2014, 2:19:22 PM").getTime()
- sdf.parse("10/17/2014, 2:18:32 PM").getTime();
System.out.println("Difference : " + (diff / (1000d * 60 )) +" Minutes");
NOTE: 1000d is used to perform floating point arithmetic here.
However, I get ...ParseException: Unparseable date: "10/17/2014, 2:19:22 PM" does anyone know why?
Because you haven't told SimpleDateFormat what the format of the string will be. Use one of the constructor that accepts a pattern string so that it knows what to expect.
Related
This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 7 years ago.
Im trying to calculate the time difference between 2 Timestamps, this is the code:
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
Timestamp currentTimestamp = new Timestamp(now.getTime());
System.out.println("Current\n"+currentTimestamp);
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("28/02/2015");
Timestamp timestampBefore = new Timestamp(date.getTime());
System.out.println("Before\n"+timestampBefore);
Timestamp calculated = new Timestamp(currentTimestamp.getTime() - timestampBefore.getTime());
System.out.println("Calculated\n"+calculated);
Output:
Current
2015-02-28 12:12:40.975
Before
2015-02-28 00:00:00.0
Calculated
1970-01-01 13:12:40.975
I can understand why it returns 1970-01-01 but why does it return 13:12:40.975 ,1 hour more?
How to calculate the difference between 2 dates so the output is like this (based on this example):
Years:0, Months:0, Days:0, Hours:12, Minutes:12, Seconds:40 ?
Update: for java below 1.8 check out http://www.joda.org/joda-time/index.html
and for java 1.8 see answer.
Similar solution here: Java 8: Calculate difference between two LocalDateTime
(1) A timestamp is a point in time. If you calculate the difference between two timestamps, the result is not a timestamp (point in time), but a duration. So it is nonsense to convert the difference to a timestamp, hence it is useless to discuss the reason why the result is strange.
(2) You should probably use the new Java 8 time API (if you are able to use Java 8):
LocalTime now = LocalTime.now();
LocalTime previous = LocalTime.of(0, 0, 0, 0);
Duration duration = Duration.between(previous, now);
System.out.println(now);
System.out.println(previous);
System.out.println(duration);
Note that this just calculates the duration between two times of a day (hour-minute-second). If your want to include date information, use LocalDateTime instead:
LocalDateTime nextFirework = LocalDate.now()
.with(TemporalAdjusters.firstDayOfNextYear())
.atTime(LocalTime.MIDNIGHT);
LocalDateTime now = LocalDateTime.now();
// duration (in seconds and nanos)
Duration duration = Duration.between(now, nextFirework);
// duration in total hours
long hours = now.until(nextFirework, ChronoUnit.HOURS);
// equals to: duration.toHours();
If you want to have 'normalized' duration in years/months/days/hours/seconds, there is suprisingly no direct support. You could convert the duration to days, hours, minutes and seconds by yourself:
long d = duration.toDays();
long h = duration.toHours() - 24 * d;
long m = duration.toMinutes() - 60 * duration.toHours();
long s = duration.getSeconds() - 60 * duration.toMinutes();
System.out.println(d + "d " + h + "h " + m + "m " + s + "s ");
But note that you will have difficulties converting the days into months and years, as there is no unique number of days per month and a year can be a leap year with 366 days. For that, you can use Period, as in opposite to Duration, this class is associated with a timeline. Unfortunately, Period does only support dates, but no times:
// period in years/months/days (ignoring time information)
Period p = Period.between(now.toLocalDate(), nextFirework.toLocalDate());
System.out.println(p); // or use p.getYears(), p.getMonths(), p.getDays()
So probably you could combine both approaches - first, compute the Period from the dates and then the Duration using the times. Note that the duration can be negative, so you'll have to take care of that in case of:
Duration dur = Duration.between(start.toLocalTime(), end.toLocalTime());
LocalDate e = end.toLocalDate();
if (dur.isNegative()) {
dur = dur.plusDays(1);
e = e.minusDays(1);
}
Period per = Period.between(start.toLocalDate(), e);
System.out.println(per.toString() + ", " + dur.toString());
I am trying to calculate the number of days between two dates.
First case :
String string = "01/03/2014";
Date dateFin = new SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE).parse(string);
string = "31/03/2014";
Date dateDebut = new SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE).parse(string);
long result = Math.abs(dateFin.getTime() - dateDebut.getTime());
System.out.println((int) (result / (long) (1000 * 3600 * 24)));
=> Result :
29
Second case :
String string = "01/03/2013";
Date dateFin = new SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE).parse(string);
string = "31/03/2013";
Date dateDebut = new SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE).parse(string);
long result = Math.abs(dateFin.getTime() - dateDebut.getTime());
System.out.println((int) (result / (long) (1000 * 3600 * 24)));
=> Result :
30
Question:
Why there is a difference between this two cases?
Thanks
The value in result is one hour less than the exact 24*30 hours. If you add 3600000 (that is 1 hour) to result, you will get the exact 24 hours (expressed in milliseconds). Apparently in France they change clocks from Winter to Summer time in the month of March. So in March there are 24*30 - 1 hours, not 24 hours. This explains why you don't have the same problem when you try the two May dates. This is my best explanation based on what I'm seeing.
See also:
http://timeanddate.com/time/change/france/paris?year=2013
http://timeanddate.com/time/change/france/paris?year=2014
You are parsing 31/03/2013 (i.e. 00:00 AM). The clock change didn't happen
until 31/03/2013, 02:00 AM. So in 2013 you have the exact 30*24 hours in March,
while in 2014 you have 1 hour less as the change happened on 3/30/2014.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I wanted to subtract and get the hours for this two date:
Time In: Jan 1 2014 5:45 PM
Time Out:Jan 2 2014 2:00 AM
I already tried using this formula and I always get a negative number. (Example: -5:0-30)
long diffHours = diff / (60 * 60 * 1000) % 24;
You may try like this:
Date d1= // start date
Date d2= // end date
long dur = d1.getTime() - d2.getTime();
long diffInSec = TimeUnit.MILLISECONDS.toSeconds(dur);
long diffInMin = TimeUnit.MILLISECONDS.toMinutes(dur);
long diffInHour = TimeUnit.MILLISECONDS.toHours(dur);
see reference
Use Math.abs(argument here) to find their absolute values
Math.abs(175)=175
Math.abs(-184)=184
Math.abs(-0)=0
Don't know if this will be much help but from my excel days I used to use this trick a lot. You could set up an if statement to check if the day changes if so then do the sum of (12- booking on time)+(12-booking off time.)
I'm sure there are easier ways to do this but I don't have access to my computer at the minute so would not be able to experiment with your formula.
You could always look into date time format as well and format Into just the time. hh:mm then perform an if again to check for changes in the day.
You can try something like this
DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
Date day1=df.parse("2014-01-01 5:45:00 PM"); // start date
Date day2=df.parse("2014-01-02 2:00:00 AM"); // end date
long milliseconds=day2.getTime()-day1.getTime(); // time gap in mil-seconds
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);
U can also calculate the time difference using SimpleDateFormat:
here is the sample code :
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy HH:mm a");
System.out.println(""+sdf.format(new Date()));
String dateStart ="Jan 1 2014 5:45 PM", dateStop="Jan 2 2014 2:00 AM";
try {
Date d1 = sdf.parse(dateStart);
Date d2 = sdf.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
diffHours = diffHours+24*diffDays;
// System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
} catch (Exception e) {
e.printStackTrace();
}
You can use Apache Commons javadoc here:
String formatPeriod = DurationFormatUtils.formatPeriod(dateAsMilis1,
dateAsMilis2), "HH:mm:ss:SSS");
I want convert the Date in long. But the hours are incorrectly calculated at pc. On Android emulator is the Time correct calculated(on emulator is UTC time). Please help
String time = "15:54";
Date date = new Date();
date.setHours(Integer.parseInt(time.substring(0, 2)));
long Hours = (date.getTime() / (1000 * 60 * 60)) % 24;
System.out.print(Hours); // 14
System.out.print("\n" + date.getHours()); // 15
When you are setting the hours to Date, java.util.Date object is independent of the concept of TimeZone. Per its javadoc here,
Although the Date class is intended to reflect coordinated universal
time (UTC), it may not do so exactly, depending on the host
environment of the Java Virtual Machine.
Hence, when you set your hours to 15, date interprets your own timezone and sets the hours to it. If there is a difference in UTC (the result you expect) and your current timezone, that difference is being reflected in your case above (14 vs 15).
To solve it, 1 option is to explicitly bring your own timezone to UTC and match the expected results:
String time = "15:54";
Date date = new Date();
java.util.TimeZone.setDefault(TimeZone.getTimeZone("UTC")); // ADDED THIS LINE
date.setHours(Integer.parseInt(time.substring(0, 2)));
long hours = (date.getTime() / (60 * 60 * 1000)) % 24;
System.out.print(hours); // NOW THIS GIVES 15
System.out.print("\n" + date.getHours()); // 15
The other option would to use Calendar class (if not jodatime) in case you want to accurately interpret the TimeZone related results.
Your question is not clear.
This kind of date-time work is much easier with the Joda-Time library.
Relying on the default time zone is troublesome. Instead, specify your time zone. It sounds like in your case the desired hour "15" is in UTC/GMT (no time zone offset). So, specify UTC.
What did you mean by "convert the Date in long"? Perhaps you meant get the milliseconds-since-epoch stored inside the Date (and in Joda-Time DateTime).
DateTime now = new DateTime( DateTimeZone.UTC );
DateTime fifteen = now.withHourOfDay( 15 );
Dump to console…
System.out.println( "now: " + now );
System.out.println( "fifteen: " + fifteen );
System.out.println( "fifteen in millis: " + fifteen.getMillis() );
System.out.println( "fifteen's hour-of-day: " + fifteen.getHourOfDay() );
When run…
now: 2014-02-14T12:43:00.836Z
fifteen: 2014-02-14T15:43:00.836Z
fifteen in millis: 1392392580836
fifteen's hour-of-day: 15
If try to call method:
private static String TIME_FORMAT = "HH:mm Z";
public static void TestDate( String time_ ) throws ParseException
{
SimpleDateFormat format = new SimpleDateFormat( TIME_FORMAT );
Date date = format.parse( time_ );
long hours = (date.getTime() / (1000 * 60 * 60)) % 24;
System.out.println( "The value 'hours' for '" + time_ + "' is '" + Long.toString( hours ) + "'" );
}
with "15:54 UTC", output wil be:
The value 'hours' for '15:54 UTC' is '15'
I am using unix timestamp to store the purchase date in my application.
sample data: 1371463066
I want to do some manipulation based on the difference in number of days and current day timestamp.
for example: If the number of days between the purchase date and current date is 5 days, then send an email regarding feedback again.
how to get the difference in days between two timestamps using java?
I have not tested it but you may try to do something like this:
Date purchasedDate = new Date ();
//multiply the timestampt with 1000 as java expects the time in milliseconds
purchasedDate.setTime((long)purchasedtime*1000);
Date currentDate = new Date ();
currentDate .setTime((long)currentTime*1000);
//To calculate the days difference between two dates
int diffInDays = (int)( (currentDate.getTime() - purchasedDate.getTime())
/ (1000 * 60 * 60 * 24) )
Unix timestamp is the number of seconds since 1.1.1970. If you have 2 unix timestamps then the difference in full days is
int diff = (ts1 - ts2) / 3600 / 24
You could try with Calendars (which will also allow you to use TimeZones):
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(1371427200l * 1000l);
Calendar newCalendar = Calendar.getInstance();
newCalendar.setTimeInMillis(1371527200l * 1000l);
// prints the difference in days between newCalendar and calendar
System.out.println(newCalendar.get(Calendar.DAY_OF_YEAR) - calendar.get(Calendar.DAY_OF_YEAR));
Output:
1