Java TimeZoneOffset time conversion - java-8

Using Jdk8.
I am trying to convert time actually just hours of the day (like 1130) into DateTime. I am trying it 2 ways as below none of them work correctly. 1130 gets converted into 11:00 and another 3:00 none of them are correct. Is there also a 3rd way naming my Time Zone.
Long ltime = Long.parseLong("1130");
Long seconds = (ltime/100)*60*60;
LocalDateTime tsutcDttime = LocalDateTime.ofEpochSecond(seconds, 0, ZoneOffset.UTC);
LocalDateTime lclDttime = LocalDateTime.ofInstant(Instant.ofEpochSecond(seconds), ZoneId.systemDefault());
System.out.println("ZoneId.systemDefault: " +ZoneId.systemDefault());
System.out.println("UTC LocalDateTime : "+ tsutcDttime);
System.out.println("Sys Def LocalDateTime : "+ lclDttime);
ZoneId.systemDefault: America/Los_Angeles
UTC LocalDateTime : 1970-01-01T11:00
Sys Def LocalDateTime : 1970-01-01T03:00
This problem got solved by below.
Part2 of this problem
For some of my time components I have a Date and for some other I don't (but I have to convert everything into datetime anyway.
How do I add the actual date when I have it? I am not seeing a method LocalDate (date)? For others will simply let default to 1970 unless a better soln exists.
The below just puts the 1970 date:
LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(secondsOfDay, 0, ZoneOffset.UTC);
But when I have a date I would like to add it to secondsOfDay and create my DateTime- How. Like Date = Jan 1 2016 + secondsOfDay
Thanks

Assuming the string "1130" means 11 hours and 30 minutes you need to do the conversion to seconds separately for the hours and minutes:
long ltime = Long.parseLong("1130");
long hoursAsSeconds = (ltime / 100) * 60 * 60;
long minsAsSeconds = (ltime % 100) * 60;
long secondsOfDay = hoursAsSeconds + minsAsSeconds;
You can then use LocalTime to get the local time given the seconds:
LocalTime localTime = LocalTime.ofSecondOfDay(secondsOfDay);
You could also get the local time directly by parsing the time like this:
LocalTime localTime = LocalTime.parse("1130", DateTimeFormatter.ofPattern("HHmm"));
From that you can get a LocalDateTime using something like:
LocalDateTime localDateTime = LocalDateTime.of(LocalDate.now(), localTime);
Or a ZonedDateTime using:
ZonedDateTime zonedDateTime = ZonedDateTime.of(LocalDate.now(), localTime, ZoneId.of("America/Los_Angeles"));

This expression is causing the issue:
Long seconds = (ltime/100)*60*60;
Division operator returns integer value so you are loosing precision here.
1130/100 = 11.3 ~ 11
11 * 60*60 = 39600
11.3 * 60*60 = 40680
Division should be the last operation in your expression:
Long seconds = (ltime*60*60)/100;

Related

What is this time format? (10 digits, 5 decimals)

So a website that I'm using has a websocket and they provide the broadcast time in the following manner:
"broadcasted_at":1574325570.71308
What is this time format and how do they generate it?
Unix epoch time ... the number of seconds that have elapsed since the Unix epoch, that is the time 00:00:00 UTC on 1 January 1970
now : 1574327074 : Thu Nov 21 03:04:34 2019
start of day : 1574316000 : Thu Nov 21 00:00:00 2019
1574325570 : 1574325570 : Thu Nov 21 02:39:30 2019
convert online : https://www.epochconverter.com/
... or download code (to build) to have command line program to perform the conversion https://github.com/darrenjs/c_dev_utils
I'm guessing the fractional part is the number of microseconds within the current second.
… and how do they generate it?
I don’t know, of course, what language or libraries your website is using. So this is just an example. To generate a value like 1574325570.71308 in Java:
Instant now = Instant.now();
double epochSeconds = now.getEpochSecond()
+ (double) now.getNano() / (double) TimeUnit.SECONDS.toNanos(1);
String result = String.format(Locale.ROOT, "%f", epochSeconds);
System.out.println("result: " + result);
When I ran this snippet just now (2019-12-15T11:18:01.562699Z), the output was:
result: 1576408681.562699
If you want exactly 5 decimals always another way is to use a DateTimeFormatter:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendValue(ChronoField.INSTANT_SECONDS)
.appendPattern(".SSSSS")
.toFormatter();
String result = formatter.format(now);
result: 1576408681.56269

How reduce one day from current in Pipeline Jenkins?

I can't reduce one day from current
def now = new Date();
print(now); // print Fri Sep 06 13:10:03 EEST 2019
print(now - 1.days); // not working
print(now - 1); // not working
Please help me. Thanks in advance
the solution works. There might be 2 problems though:
- the snippet you wrote has to be included in a script if you plan to execute it in a stage
- the DateGroovyMethods is not allowed to be used by default. You need administrator rights and to check the build log to allow the execution of that stuff.
The error will look like this:
Scripts not permitted to use staticMethod org.codehaus.groovy.runtime.DateGroovyMethods minus java.util.Date int. Administrators can decide whether to approve or reject this signature.
This is my test example:
pipeline {
agent any
stages {
stage('MyDate test') {
steps {
script {
def date = new Date()
print date
print date - 1
}
}
}
}
}
EDIT:
If you are not an administrator, you can replace the script block with sh 'date -d "-1 days"'
You can also use minus(1) instead of - 1:
def now = new Date();
print(now);
print(now.minus(1))
The best thing to do is to skip the use of Date entirely. java.util.Date is literally the oldest java implementation of date and time. The newest comes with Java 8. You can do it like this:
groovy:000> java.time.LocalDateTime.now().minusDays(1)
===> 2019-09-08T12:07:30.835557
groovy:000>
You can convert from Date to LocalDateTime as well if needed.
(Java syntax used here, as I do not know Groovy.)
tl;dr
Subtract 24-hours.
Instant.now().minus( Duration.ofHours( 24 ) ) // UTC.
…or…
Subtract one calendar day.
ZonedDateTime.now( ZoneId.of( "America/New_York" ) ).minusDays( 1 ) ) // Time zone for Toledo, Ohio, US.
java.time
Never use java.util.Date. That terrible class was supplanted years ago by the modern java.time classes with the adoption of JSR 310. Specifically replaced by Instant.
I can't reduce one day from current
What do you mean by “one day”?
Generic 24-hour days
Do you mean to subtract 24-hours?
Duration d = Duration.ofHours( 24 ) ;
Instant instant = Instant.now() ;
Instant twentyFourHoursAgo = instant.minus( d ) ;
The Instant class represents a moment in UTC with a resolution of nanoseconds.
Run this code live at IdeOne.com.
instant.now().toString(): 2019-09-09T18:48:17.106438Z
twentyFourHoursAgo.toString(): 2019-09-08T18:48:17.106438Z
Calendar days
Do you mean to subtract one calendar day?
This requires a time zone. For any given moment, the date varies around the globe by time zone. It may be “tomorrow” in Tokyo Japan while still “yesterday” in Toledo Ohio US.
Specify a time zone with ZoneId to capture the current moment as seen through the wall-clock time used by the people of a particular region in a ZonedDateTime object.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
ZonedDateTime oneDayAgo = zdt.minusDays( 1 ) ;
Run this code live at IdeOne.com.
zdt.toString(): 2019-09-10T03:48:17.147539+09:00[Asia/Tokyo]
oneDayAgo.toString(): 2019-09-09T03:48:17.147539+09:00[Asia/Tokyo]
Convert
If you must have a java.util.Date object to interoperate with old code not yet updated to java.time, you can convert. See the new to…/from… conversion methods added to the old classes.
java.util.Date javaUtilDate =
Date.from( Instant.now().minus( Duration.ofHours( 24 ) ) ) ;
…or…
java.util.Date javaUtilDate =
Date.from( ZonedDateTime.now( ZoneId.of( "Asia/Tokyo" ) ).minusDays( 1 ) ) ) ;
Keep in mind that java.util.Date.toString method tells a lie, dynamically applying the JVM’s current default time zone while generating the text. One of many reasons to avoid this badly-designed class.

Ruby: how to convert VARIANT DATE to datetime

In my project i get from external system date&time in VARIANT DATE type and need to convert it to datetime (i.e. 43347.6625 => 04/09/2018 16:29:59).
Do you know how to do it in ruby? what is the best approach? I did not find any ruby built-in method to do such a conversion...
here a method to do the calculation, the date you give is not correct, it should be what this method is returning, check with https://planetcalc.com/7027/
def variant2datetime variant
# number of days after 1-1-1900 minus 2 days for starting with 0
# and having a day that didn't exist because 1900 wasn't a leap year
date = Time.new("1900-01-01") + (variant.to_i - 2) * 24 * 60 * 60
fraction = variant % 1
hours = (fraction - fraction.to_i) * 24
minutes = (hours - hours.to_i) * 60
seconds = (minutes - minutes.to_i) * 60
Time.new(date.year, date.month, date.day, hours.to_i, minutes.to_i, seconds.to_i)
end
variant2datetime 43347.6625 # 2018-09-04 15:53:59 +0200

Not able to compare java.util.Date with Timestamp in Oracle

I am not able to compare java.util.Data with Oracle Timestamp
Date stored in address table is like 29-JUL-13 07.15.57.529000000 PM
My Address class is like below
#Entity
#org.hibernate.annotations.Entity(dynamicUpdate = true)
#Table(name = "address")
public class Address {
#Id
#GeneratedValue(generator = "assigned-by-code")
#GenericGenerator(name = "assigned-by-code", strategy = "assigned")
#Column(name = "id")
private String id;
#Type(type = "timestamp")
#Column(name = "lastaccesstimestamp")
private Date lastAccessTimestamp;
getter and setter
}
#Query("from Address a where a.associationId =:associationId and a.lastAccessTimestamp >=:lastAccessTimestamp")
List<Address> findLatestUpdatedAddresses(
#Param("lastAccessTimestamp") Date lastAccessTimestamp,
#Param("associationId") String associationId);
And lastAccessTimestamp in findlatestUpdateAddress method is Calendar.getInstance().getTime()(e.g Mon Jul 29 10:10:09 IST 2013).
It is giving proper result for month, day and year compression but when there is change in minute, second or hour it is not giving proper result.
For Example if lastAccessTimestamp is Mon Jul 29 10:10:09 IST 2013 and DB date is 30-JUL-13 07.15.57.529000000 PM it will return result
but if lasteAccessTimestamp is Mon Jul 30 07:09:09 IST 2013 it is not giving any result I think hour minute and second part is not considered in compression.
In short for month date and year compression is working fine but for minute second and hour it is not working.
Any suggestion will be appreciated even if there is any alternative solution will be accepted.
Please, try to replace your:
#Type(type = "timestamp")
with
#Temporal(TemporalType.TIMESTAMP)
This annotation will tell hibernate to include hour/min/sec as it handles the object mapping.

how to convert timestamp on windows ping -s option to date?

ping [SomeIP] -s 4 -t > ping.log
result of that command is like below.
Reply from [SomeIP] : bytes=32 time=4ms TTL=125
Timestamp: [HOP] : 83842793 ->
[HOP] : 83842793 ->
[HOP] : 83832797 ->
[HOP] : 83842793
how can i convert this timestamp to datetime?
The timestamp you get is number of miliseconds past midnight UTC time. Date is current date.
Conversion from here is simple:
time = timestamp /1000
hours = (time / 3600)
minutes = (time / 60) - (hours * 60)
seconds = time mod 60
If anyone is looking for a quick way to convert date/time to timestamp and back, I just came across this chrome extension and I think it's really great! It's the quickest cross platform method and I use it constantly since it parses plenty of date formats and is really fun nice to use.

Resources