Get all milliseconds from LocalTime Java [duplicate] - java

This question already has an answer here:
How can I return LocalDate.now() in milliseconds?
(1 answer)
Closed 2 years ago.
I need to know how to get LocalTime to milliseconds
LocalTime lunchTime = LocalTime.parse("01:00:00",
DateTimeFormatter.ISO_TIME);
If i am going to execute lunchTime.getMinute() i only get 0 and lunchTime.getHour() i only get 1 as an hour. How to get value in milliseconds?

Try getting nano seconds or seconds and converting to milliseconds (depending on what precision you're dealing with).
lunchTime.toNanoOfDay() / 1e+6
lunchTime.toSecondOfDay() * 1e+3

If you want the millisecond of the day (in other words the count of milliseconds since 00:00), there is a ChronoField enum constant exactly for that:
LocalTime lunchTime = LocalTime.parse("01:00:00");
int millisecondOfDay = lunchTime.get(ChronoField.MILLI_OF_DAY);
System.out.println("Lunch is at " + millisecondOfDay + " milliseconds of the day");
Output:
Lunch is at 3600000 milliseconds of the day
(1 AM is probably a funny time for lunch for some, but for the sake of demonstration and of using your own example.)
The date and time classes of java.time generally have got a get method that accepts a TemporalField argument. LocalTime is no exception to this rule. The most common thing to do when calling get() is to pass a ChronoField constant. The method is very versatile for getting values from the date-time object for which no getXxx method is provided.
Doc link: ChronoField.MILLI_OF_DAY

You can use System.currentTimeMillis(), refer https://currentmillis.com/
Also, please refer https://stackoverflow.com/a/26637209/1270989 to followup on parsing date in your choice of format.
Also, if you trying to get local time in your timezone from an application running in different timezone please follow comment https://stackoverflow.com/a/319398/1270989

Related

Java millis time with hourly resolution

How do I get java time millis in UTC ignoring the minutes and seconds.
For instance :
If it is October 10 2019, 1:10:59 AM , it should get the Time or millis for
October 10 2019, 1 AM.
Summary:
Instant
.now()
.truncatedTo(
ChronoUnit.HOURS
)
.toEpochMilli()
1570600800000
java.time, the modern Java date and time API has got exactly the method you need: many of the classes have a truncatedTo method for needs like yours.
Instant now = Instant.now();
System.out.println("Rough milliseconds: " + now.toEpochMilli());
Instant currentWholeHour = now.truncatedTo(ChronoUnit.HOURS);
System.out.println("Milliseconds ignoring minutes and seconds: "
+ currentWholeHour.toEpochMilli());
When running this snippet just now the output was:
Rough milliseconds: 1570604053787
Milliseconds ignoring minutes and seconds: 1570600800000
I know very well that the first line is what you asked not to have. I only included it for you to see the difference.
The truncation happens in UTC. If you are in a time zone whose offset is not a whole number of hours from UTC, the results may not be as you had expected. Examples of such time zones include Asia/Kathmandu, America/St_Johns some of the year also Australia/Lord_Howe.
Link: Oracle tutorial: Date Time
You can use LocalDate#atTime:
LocalDate.now().atTime(LocalDateTime.now().getHour(), 0, 0);
This will give you current date with hour and minutes and seconds set to 0.
And to get milliseconds in UTC:
LocalDate.now().atTime(LocalDateTime.now().getHour(), 0, 0).toInstant(ZoneOffset.UTC).toEpochMilli();
Jon Skeet notices, that calling now might give unexpected results in corner cases. To be sure, we can call it once and then convert it to LocalDate with mentioned solution:
var currentTime = LocalDateTime.now();
var currentDate = currentTime.toLocalDate();
Or the other way around - get LocalDate first and use LocalDate#atStartOfDay.
Given that you're interested in UTC milliseconds, and there are a whole number of milliseconds per hour, you can do this with simple arithmetic. For most calendrical computations I really wouldn't recommend that, but in this case I think it's the simplest approach. Something like this:
private static final long MILLISECONDS_PER_HOUR = TimeUnit.HOURS.toMillis(1);
// Injecting a clock makes the method testable. You can use Clock.systemUTC()
// for the system clock.
public static long truncateMillisToHour(Clock clock) {
long millisSinceEpoch = clock.millis();
// Truncate to the nearest hour
long hoursSinceEpoch = millisSinceEpoch / MILLISECONDS_PER_HOUR;
// Then multiply up again
return hoursSinceEpoch * MILLISECONDS_PER_HOUR;
}
Note that if the clock is for before the epoch, this will round up to the nearest hour, but if you're taking the genuine "current time" then that's unlikely to be a problem.
(I wrote this answer before seeing Ole V.V.'s answer with truncatedTo, which is a very nice approach.)

In java language, how to convert nano seconds value, for example 1568694302232954486 and 1568703521360049938 into a Java Date object? [duplicate]

This question already has answers here:
convert nanoseconds since 1904 to a valid java date
(4 answers)
Closed 3 years ago.
I have many long numbers which look like 1568694302232954486 and 1568703521360049938, and I need to convert each of them into a Java Date object.
How to implement the above requirement in Java 8?
I also need transform the nanosecond value into elasticsearch's timestamp and have found the correct way; thanks for all the help!
Just for those who need it, the following code block has passed the test. It's actually part of a logstash configuration file:
ruby {
init => ""
code => "
event.set('time_local',event.get('time_local').to_f*0.000001)
"
}
date {
#15/Aug/2019:14:46:19 +0800 [02/Sep/2019:09:28:33 +0800]
match => [ "time_local" , "yyyy-MM-dd HH:mm:ss,SSS","UNIX_MS"]
timezone => "Asia/Shanghai"
target => "#timestamp"
}
java.time
It’s very easy when you know how. While the second parameter of the two-arg Instant.ofEpochSecond() is named nanoAdjustment, it has type long, and the method accepts the full nano value being passed in this parameter. So just pass 0 as the seconds and leave the conversion to the method:
Instant instant1 = Instant.ofEpochSecond(0, 1_568_694_302_232_954_486L);
System.out.println(instant1);
Instant instant2 = Instant.ofEpochSecond(0, 1_568_703_521_360_049_938L);
System.out.println(instant2);
Output is:
2019-09-17T04:25:02.232954486Z
2019-09-17T06:58:41.360049938Z
If you do need an old-fashioned Date object for a legacy API that you cannot change or don’t want to upgrade just now:
Date oldfashionedDate1 = Date.from(instant1);
System.out.println(oldfashionedDate1);
On my computer the converted Date was printed as:
Tue Sep 17 06:25:02 CEST 2019
Generally do avoid the Date class, though. It is poorly designed and long outdated. Working with java.time, the modern Java date and time API, is so much nicer.
Link: Oracle tutorial: Date Time explaining how to use java.time.
If you want it as a Date object, then you are going to lose some information, because Date only has millisecond precision. Date is also obsolete in Java 8, so if you are using Java 8 or above, consider using Instant instead.
Here is how to convert to Date. Don't do this unless you really have to.
long nano = 1568694302232954486L;
Date d = new Date(nano / 1000000); // 1000000 is how many nanoseconds there are in a millisecond
Instant on the other hand has nanosecond precision, and is what you should be doing:
// 1000000000 is how many nanoseconds there are in a second.
Instant i = Instant.ofEpochSecond(nano / 1000000000, nano % 1000000000);

How to properly use ThreeTenABP to get the time in milliseconds between two dates based on UTC

I'm using this library I just discovered which is supposedly less heavier than Joda time for android and I said what the heck, let's use it. But now I'm struggling to find any good examples on the web about how to use it, besides these two methods I have:
// ZonedDateTime contains timezone information at the end
// For example, 2011-12-03T10:15:30+01:00[Europe/Paris]
public static ZonedDateTime getDate(String dateString) {
return ZonedDateTime.parse(dateString).withZoneSameInstant(ZoneId.of("UTC"));
}
public static String formatDate(String format, String dateString) {
return DateTimeFormatter.ofPattern(format).format(getDate(dateString));
}
So how can I get the difference between two dates with this library?
There are several options depending on what you require from the difference you obtain.
It’s easiest to find the difference measured in some time unit. Use ChronoUnit.between. For example:
ZonedDateTime zdt1 = getDate("2011-12-03T10:15:30+01:00[Europe/Paris]");
ZonedDateTime zdt2 = getDate("2017-11-23T23:43:45-05:00[America/New_York]");
long diffYears = ChronoUnit.YEARS.between(zdt1, zdt2);
System.out.println("Difference is " + diffYears + " years");
long diffMilliseconds = ChronoUnit.MILLIS.between(zdt1, zdt2);
System.out.println("Difference is " + diffMilliseconds + " ms");
This prints:
Difference is 5 years
Difference is 188594895000 ms
I am using your getDate method, so the format required is that of ZonedDateTime (modified from ISO 8601), for example 2011-12-03T10:15:30+01:00[Europe/Paris]. Seconds and fraction of second are optional, as is time zone ID in square brackets.
BTW you don’t need to convert to UTC before finding the difference. You will get the same result even if you leave out that conversion.
You may also get the difference in years, months and days. The Period class can give you this, but it cannot handle time of day, so convert to LocalDate first:
Period diff = Period.between(zdt1.toLocalDate(), zdt2.toLocalDate());
System.out.println("Difference is " + diff);
Difference is P5Y11M21D
The output means a period of 5 years 11 months 21 days. The syntax may feel a little strange at first, but is straightforward. It is defined by the ISO 8601 standard. In this case the time zone matters since it is never the same date in all time zones.
To get the difference in hours, minutes and seconds use the Duration class (I am introducing a new time since using Duration for nearly 6 years would be too atypical (though possible)).
ZonedDateTime zdt3 = getDate("2017-11-24T18:45:00+01:00[Europe/Copenhagen]");
Duration diff = Duration.between(zdt2, zdt3);
System.out.println("Difference is " + diff);
Difference is PT13H1M15S
A period of 13 hours 1 minute 15 seconds. The T that you already know from 2011-12-03T10:15:30+01:00[Europe/Paris] here too separates the date part from the time part so you know that in this case 1M means 1 minute, not 1 month.

How do I create a java.sql.Date object initialized to current time? It keeps getting rounded off to midnight time [duplicate]

This question already has an answer here:
How to save time using java.sql.Date?
(1 answer)
Closed 5 years ago.
I am trying to create a java.sql.Date object initialized to current time but it was being rounded off to midnight time . Can any of you help? I attempted below but it did not work.
new Date(new java.util.Date().getTime())
I can't explain it better than the Javadoc does:
A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT.
To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.
If you need time information as well, you might use java.sql.Timestamp.

Java same Dates containing different time in milli seconds [duplicate]

This question already has answers here:
How to check if 2 dates are on the same day in Java
(4 answers)
Closed 8 years ago.
I have two calendar objects, they seems to contain same dates but the compareTo() method is returning -1 as result, Can any one explain the reason behind this.
On debugging the two Calendar objects, the result is shown as :
2014-06-01T00:00:00.000Z
for both calendar objects but the compareTo() is returning -1. Even the long time in millis for both dates are different.
Well, have a look at the Calendar code (this is from JDK 1.7.0-13):
public int compareTo(Calendar anotherCalendar) {
return compareTo(getMillisOf(anotherCalendar));
}
private int compareTo(long t) {
long thisTime = getMillisOf(this);
return (thisTime > t) ? 1 : (thisTime == t) ? 0 : -1;
}
It should be obvious that if the two Calendar's have different millis, then they're different as per the second method.
In any case, the millis in your example should not both represent 2014-06-01T00:00:00.000Z so there's another problem in your code. Try this:
Timestamp ts1 = new Timestamp( 1401561000000L );
Timestamp ts2 = new Timestamp( 1401595200000L );
System.err.println( ts1 );
System.err.println( ts2 );
Outputs:
2014-05-31 20:30:00.0
2014-06-01 06:00:00.0
Cheers,
The milliseconds number is the "offical" time in Java. However, for a variety or reasons, there are numbers with the same date/time which have different numbers of milliseconds. Then normal reason is clock adjustments. E.g. Sometimes you have to add a second or two to account for irregularities in the earth's orbit. The other big source is when regions were first brought into the UTC, then some time zones moved hours.
THere is also the common source for these things: DST.
This will happen twice a year when you move to daylight saving time, on the one hand there are date/times which do not exists, as they were "skipped", and there are other times which happened twice, as the clock gets reset at midnight, so 11pm-midnight happens twice on the same day.
If you want to just compare the minutes and ignore the milliseconds or seconds do this:
You need to use
cal.set(Calendar.MILLISECOND, 0);
and possibly as well
cal.set(Calendar.SECOND, 0);
if you just need the minutes to match.
Quick explanation of what is going on:
The JavaDoc for Calendar states:
Compares the time values (millisecond offsets from the Epoch)
represented by two Calendar objects.
So you acknowledge that ".. long time in millis for both dates are different .."
#JonSkeet says in this question:
Calendar.setTime takes a java.util.Date, which is just a wrapper
around a long indicating the number of milliseconds since midnight Jan
1st 1970, UTC. It's not "in the format MM/dd/yyy" - that's a string
representation, not a java.util.Date. If it happens to print something
out in the format MM/dd/yyyy, that's just what Date.toString is doing
for you - it's not inherently part of the format.
This should answer your question about what is going on.
Note: java.util.Date has the same problem.
PS. A lot of people say use Joda Time, which I have heard is going to be in Java 8, but I have not personally tried it. If you are going to be using a lot of date code, I'd recommend you use it.
I invoked compareTo on Date instead of Calendar and got the correct result. It might be because of the fact that Calendar stores Timezone information but Date object does not.
Thanks

Categories