Convert long Timestamp to shorter Timestamp - java

I have a Timestamp in this format: 1479912701805
If you check on
http://www.epochconverter.com/ you can see that date is
GMT: Wed, 23 Nov 2016 14:51:41.805 GMT
Now I need to shorten that long to
1479859200 which is 3 number shorter, I guess milisecs

From your data in example, you need to remove hours, minute and seconds from
the value first. Using the % will be enough.
Remove the remainder of the number of milliseconds of a day from this value.
l -= l% (1000*60*60*24);
A small example :
long l = 1479912701805l;
Calendar c = Calendar.getInstance();
c.setTimeInMillis(l);
System.out.println(c.getTime());
l -= l% (1000*60*60*24);
c.setTimeInMillis(l);
System.out.println(c.getTime());
Wed Nov 23 15:51:41 CET 2016
Wed Nov 23 01:00:00 CET 2016
PS : The remaining hours is the time zone ;)
1479912701805
1479859200000
Then, just divide this by 1000 to remove the 3 first digit

divide by 1000 to get secs? linked site is recognizing "long" (milisecs) timestamps and shows: Assuming that this timestamp is in milliseconds, then calculates after /1000 division, so both 1479859200 and 1479859200000 are same date on this site
note that your examples are 1479912701805 and 1479859200 - same date only, but not hour/min/secs
there is also method:
long timeMillis = 1479859200000;
long timeSecs = TimeUnit.MILLISECONDS.toSeconds(timeMillis);
which is of course dividing by 1000, but you may find other TimeUnit methods useful

Related

How to find day difference between 2 timestamp in java [duplicate]

This question already has answers here:
How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?
(8 answers)
Calculate days between two Dates in Java 8
(14 answers)
Closed 4 years ago.
I want to calculate how many day difference between 2 timestamps, but i do not want to consider the time difference.
For example :
long time1 = 1546258765000 (Mon 31 December 2018 13:19:25)
long time2 = 1546005915367 (Fri 28 December 2018 15:05:15)
The result should be 3, 3 days left for expire...
Due to time I get 2 from this method:
TimeUnit.DAYS.convert(time1 - time2 , TimeUnit.MILLISECONDS))
I just need to set the time same for both time1 and time2, and then go back to timestamp and calculate like this... but I am not sure what is the best way to do it.
NOTE: As noted by Ole V.V: this only works for UTC. Since timestamps are always on UTC, if you are in another timezone it might return undesired results. Example:
In GMT + 1:
time1 = 1546216200000L (Mon 31 December 2018 01:30:00) (31/12 00:30 on UTC)
time2 = 1545953400000L (Fri 28 December 2018 00:30:00) (27/12 11:30 on UTC)
This will result in a 4 days difference, since that's the difference on UTC.
To compensate that, you should offset the difference so the timestamps show your current time, instead of UTC time. (If you are in GMT+1, for example, you will need to add 1 hour (3600000 ms) to each timestamp).
I believe the simplest way might be using module:
final long MILLIS_PER_DAY = 1000*60*60*24;
long time1 = 1546258765000L; // (Mon 31 December 2018 13:19:25)
long time2 = 1546005915367L; // (Fri 28 December 2018 15:05:15)
// Set both times to 0:00:00
time1 -= time1 % MILLIS_PER_DAY;
time2 -= time2 % MILLIS_PER_DAY;
And then
TimeUnit.DAYS.convert(time1 - time2 , TimeUnit.MILLISECONDS))
should give you the desired result.
Convert millis to LocalDateTime then calculate the Duration:
LocalDateTime start = LocalDateTime
.ofInstant(Instant.ofEpochMilli(1546005915367L), ZoneId.systemDefault())
.truncatedTo(ChronoUnit.DAYS);
LocalDateTime stop = LocalDateTime
.ofInstant(Instant.ofEpochMilli(1546258765000L), ZoneId.systemDefault())
.truncatedTo(ChronoUnit.DAYS);
Duration duration = Duration.between(start, stop);
long dayDifference = duration.toDays();
Converts the given time duration in the given unit to this unit.
Conversions from finer to coarser granularities truncate, so lose precision. For example, converting 999 milliseconds to seconds results in 0.
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html#convert(long,%20java.util.concurrent.TimeUnit)
Use joda-time lib:
long time1 = 1546258765000L;
long time2 = 1546005915367L;
DateTime dateTime1 = new DateTime(time1);
DateTime dateTime2 = new DateTime(time2);
int hours = Hours.hoursBetween(dateTime2, dateTime1).getHours();
int days = hours % 24 == 0 ? hours / 24 : hours / 24 + 1;
System.out.println(days);
joda-time lib has method to calculate days between two timeļ¼Œbut the result is not your want:
Days.daysBetween(dateTime1,dateTime2).getDays()

Difference between Calendar.HOUR and Calendar.HOUR_OF_DAY?

What is the difference between Calendar.HOUR and Calendar.HOUR_OF_DAY ?
When to use Calendar.HOUR and Calendar.HOUR_OF_DAY ?
I am confused sometime Calendar.HOUR this works fine and othertime Calendar.HOUR_OF_DAY this works fine. What they return in the form of int?
I have read this documentation but not understood the difference.
Any suggestions
Thanks.
From http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#HOUR:
Calendar.HOUR = Field number for get and set indicating the hour of the morning or afternoon. HOUR is used for the 12-hour clock. E.g., at 10:04:15.250 PM the HOUR is 10.
Calendar.HOUR_OF_DAY = Field number for get and set indicating the hour of the day. HOUR_OF_DAY is used for the 24-hour clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.
This code will help you understand better
import java.util.Calendar; import java.util.GregorianCalendar;
public class test{ public static void main(String[] args) {
GregorianCalendar gc = new GregorianCalendar(2013, 8, 15, 21, 69,55);
//minutes = 69 is equal to 1 hour and 09 minutes. This hour will add to Hour place (21+1 = 22)//Sun Sep 15 22:09:55 IST 2013
p(gc, Calendar.YEAR); //gives year
p(gc, Calendar.MONTH); // gives month staring at 0 for January
p(gc, Calendar.DATE); // date
p(gc, Calendar.DAY_OF_WEEK);// Sunday=1, Monday=2, .....Saturday -7
p(gc, Calendar.WEEK_OF_MONTH);//what week its running in week ,whether its first or second;
p(gc, Calendar.DAY_OF_WEEK_IN_MONTH);//In this case, How may times does Sunday is repeating in the month = 3;
p(gc, Calendar.DAY_OF_YEAR);//count of the day in the year
p(gc, Calendar.HOUR);//12 hour format. if the time is 22:09:55, answer would be (22-12)=10
p(gc, Calendar.HOUR_OF_DAY);// hour of day that is 22 (24h format)
p(gc, Calendar.MINUTE);// 09
p(gc, Calendar.SECOND);// 55
System.out.println();
System.out.println(gc.getTime());
}
static void p(Calendar c, int type) {
System.out.print(c.get(type) + "-");
}
}
*output :
2013-8-15-1-3-3-258-10-22-9-55-
Sun Sep 15 22:09:55 IST 2013
*
output Date visualization

SimpleDateFormat format date between to dates issue

I need to calculate period between two dates, one date is now. And I'm using SimpleDateFormat for formatting date.
public String getPeriod(Date endDate) {
String format;
Date now = new Date();
long period = endDate.getTime() - now.getTime();
if (now.after(endDate)) {
return "passed";
} else {
if (period < 1000 * 60 * 60)
format = "m'M' s'S'";
else if (period < 1000 * 60 * 60 * 24)
format = "k'H' m'M'";
else
format = "'Too much'";
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.format(new Date(period)) + " / for testing - " + period / 3600000 + " hours";
}
}
As a result I have following input for example if endDate equals Wed Nov 12 13:30:02 EET 2014 (EST):
1 H 36 M / for testing - 22 hours
As you can see my test calculation and format's method result do not match. What am i doing wrong?
The difference is due to the timezone. For example, in my case, given as the parameter the time that would be in an hour, I get 3H as output, because the date would be Thu Jan 01 03:00:00 EET 1970. Notice the EET (I'm from Eastern Europe).
Your code would work if you'd notify java to use GMT time, as it says in the new Date(long) description:
Allocates a Date object and initializes it to represent the specified
number of milliseconds since the standard base time known as "the
epoch", namely January 1, 1970, 00:00:00 GMT.
Also, keep in mind that Date does not give perfect results. Using programatically determined dates exactly 1h appart (no millies / minutes difference), date calculations give an offset of 59 minutes, 59 seconds and 999 milies. If you require more exact values, you should use nanoseconds.
However, the other commenters are right. You should not use Java Date / Calendar in such a way, as it is a bug factory (this is only one corner case). You should check out other libraries (such as yoda time), or if you only need simple calculations such as this, do it yourself.
Hope it helps.

Java code to calculate number of mid nights (00:00:00) in a date range

I am trying to write a java block to find the number of mid-nights in a particular date range.
For example:
begin date: 05/01/2014 00:00:00
end date : 05/03/2014 00:00:00
this range has 3 mid-nights in it.
or
begin date : 05/01/2014 00:00:00
end date : 05/02/2014 23:59:59
this has only one.
It basically has to tell me how many times the time "00:00:00" occurrs in the date range.
Please help me out. I tried many approaches but none work correct.
I would just count the days (the actual dates), and add one if the earliest date has a time of 00:00:00.
begin date: 05/01/2014 00:00:00 end date : 05/03/2014 00:00:00
03 - 01 = 2 days.
Since the begin date has a time of 00:00:00, then add one:
2 + 1 = 3 midnights.
or
begin date : 05/01/2014 00:00:00 end date : 05/02/2014 23:59:59
02 - 01 = 1 day.
Since the begin date has a time of 00:00:00, then add one:
1 + 1 = 2 midnights.
Also,
begin date : 5/01/2014 23:59:59 end date : 5/02/2014 00:00:01
02 - 01 = 1 day.
Since the begin date doesn't have a time of 00:00:00, then don't add one:
1 midnight.
The answer using Joda-Time is not correct. As #khriskooper has noted the count of midnights between
2014-05-01 00:00:00 and 2014-05-02 23:59:59
is not one but two midnights!
So here the correction using Joda-Time (not tested), but it could also be any other library which supports day-range calculations (not true for old Java-pre8). I leave out the timezone detail because I do not consider it as really relevant for the question. If OP wants he can replace LocalDateTime by DateTime and apply a timezone.
LocalDateTime ldt1 = new LocalDateTime(2014, 5, 1, 0, 0, 0);
LocalDateTime ldt2 = new LocalDateTime(2014, 5, 2, 23, 59, 59);
int days = Days.daysBetween(ldt1.toLocalDate(), ldt2.toLocalDate()).getDays();
if (ldt1.toLocalTime().equals(new LocalTime(0, 0))) {
days++;
}
One option is to use Joda-Time library:
DateTimeZone zone = DateTimeZone.forID("America/New_York");
int days = Days.daysBetween(new DateTime(startDate, zone), new DateTime(endDate, zone)).getDays();
I think this is the easiest way. The drawback is that you need one more library..
Hope this can help!
Using Joda's DateTime library (one I would recommmend anyway), an elegant way to do so would be:
private int getNumberOfNights(DateTime start, DateTime end) {
int nightCount = 0;
DateTime tempEnd = new DateTime(end);
while (tempEnd.withTimeAtStartOfDay().isAfter(start)) {
nightCount++;
tempEnd = tempEnd.minusDays(1);
}
return nightCount;
}
... or if you want to avoid a while loop:
private int getNumberOfNights(DateTime start, DateTime end) {
int nightCount = Days.daysBetween(start, end).getDays();
DateTime leftOver = new DateTime(end.minusDays(nightCount));
if (leftOver.withTimeAtStartOfDay().isAfter(start)) {
nightCount++;
}
return nightCount;
}
With Java 7
public long countDays(Date dtStart, Date dtEnd) {
long startDay = TimeUnit.DAYS.convert(dtStart.getTime(), TimeUnit.MILLISECONDS)
long endDay = TimeUnit.DAYS.convert(dtEnd.getTime(), TimeUnit.MILLISECONDS)
return endDay - startDay
}

Why is this code giving me a date 39k years in the future?

I've written a method that returns the milisecond value of a string formatted date, and for some reason it's giving me dates 39000 years in the future. any ideas why?
private long getTimeInMs(String currentStartTimeString) {
//String newDateString = currentStartTimeString.substring(6,10)+"-"+currentStartTimeString.substring(3, 5)+"-"+currentStartTimeString.substring(0, 2)+ "T" + currentStartTimeString.substring(11);
String newDateString = currentStartTimeString.substring(0,19);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long timeInMs;
try {
timeInMs = df.parse(newDateString).getTime();
} catch (ParseException e) {
log.error("Failed to parse current Start Time",e);
return 0;
}
return timeInMs;
}
If I enter the date string "2009-07-07 10:51:01.15" it returns 1246960261000 which is actually Wed Aug 06 41484 11:16:40 GMT+0100 (GMT Daylight Time)
Okay I think the issue is that it's giving ms past the Java epoc and I'm evaluating it against the unix epoch...
I'm guessing that you interpreted the returned value from getTime() as if it was a Unix time_t value. It's not - it's milliseconds past the Java epoch, not seconds past the Unix epoch.
It looks fine to me. The Date object that comes out of the parse toString's to "Tue Jul 07 10:51:01 BST 2009" (I'm in the UK timezone here), but that should make no big difference). The millis value of 1246960261000 is correct, why do you think that evaluates to the far future? How did you calculate that?
The value is correct, in fact :
(((((1246989061000 / 1000) / 60)/60)/24)/365)
gives
39.54176373033992 years which is about correct given that 0 is 1970.
running your code in Java 6, i get 1246978261000, which turns out to be correct.
System.out.println(new Date(timeInMs));
returns
Tue Jul 07 10:51:01 EDT 2009
edit:
to confirm others' suggestions that you are looking at seconds (not millis):
System.out.println(new Date(timeInMs*1000));
yields
Mon Mar 02 13:16:40 EST 41485

Categories

Resources