Get duration in microseconds - java-8

Considering the exemple :
final Duration twoSeconds = Duration.ofSeconds(2);
// final long microseconds = twoSeconds.get(ChronoUnit.MICROS); throws UnsupportedTemporalTypeException: Unsupported unit: Micros
final long microseconds = twoSeconds.toNanos() / 1000L;
System.out.println(microseconds);
I wonder if there is a nicer way to get a Duration in microseconds than converting manually from nanoseconds.

I wouldn’t use the java.time API for such a task, as you can simply use
long microseconds = TimeUnit.SECONDS.toMicros(2);
from the concurrency API which works since Java 5.
However, if you have an already existing Duration instance or any other reason to insist on using the java.time API, you can use
Duration existingDuration = Duration.ofSeconds(2);
// Since Java 8
long microseconds8_1 = existingDuration.toNanos() / 1000;
// More idiomatic way
long microseconds8_2 = TimeUnit.NANOSECONDS.toMicros(existingDuration.toNanos());
// Since Java 9
long microseconds9 = existingDuration.dividedBy(ChronoUnit.MICROS.getDuration());
// Since Java 11
long microseconds11 = TimeUnit.MICROSECONDS.convert(existingDuration);

Based on Holger answer, my favorite would be:
final long microseconds = TimeUnit.NANOSECONDS.toMicros(twoSeconds.toNanos())

Related

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.

Convert TMediaPlayer->Duration to min:sec (FMX)

I'm working with the TMediaPlayer1 control in an FMX app using C++ Builder 10.2 Version 25.0.29899.2631. The code below runs fine in Win32 and gives the expected result after loading an mp3 file that is 35 minutes, 16 seconds long.
When i run this same code targeting iOS i get the following error:
[bcciosarm64 Error] Unit1.cpp(337): use of overloaded operator '/' is ambiguous (with operand types 'Fmx::Media::TMediaTime' and 'int')
Here is my code that takes the TMediaPlayer1->Duration and converts it to min:sec,
UnicodeString S = System::Ioutils::TPath::Combine(System::Ioutils::TPath::GetDocumentsPath(),"43506.mp3");
if (FileExists(S)) {
MediaPlayer1->FileName = S;
int sec = MediaPlayer1->Duration / 10000000; // <-- this is problem line
int min = sec / 60;
sec = sec - (60 * min);
lblEndTime->Text = IntToStr(min) + ":" + IntToStr(sec);
}
How should i be doing that division?
UPDATE 1: I fumbled around and figured out how to see the values with this code below. When i run on Win32 i get 21169987500 for the Duration (35 min, 16 seconds) and i get 10000000 for MediaTimeScale - both correct. When i run on iOS i get 0 for Duration and 10000000 for MediaTimeScale. But, if i start the audio playing (e.g. MediaPlayer1->Play();) first and THEN run those 2 showmessages i get the correct result for Duration.
MediaPlayer1->FileName = S; // load the mp3
ShowMessage(IntToStr((__int64) Form1->MediaPlayer1->Media->Duration));
ShowMessage(IntToStr((__int64) MediaTimeScale));
It looks like the Duration does not get set on iOS until the audio actually starts playing. I tried a 5 second delay after setting MediaPlayer1->Filename but that doesn't work. I tried a MediaPlayer1->Play(); followed by MediaPlayer->Stop(); but that didn't work either.
Why isn't Duration set when the FileName is assigned? I'd like to show the Duration before the user ever starts playing the audio.

How to convert time::Tm to u64 for JWT expiration date

I'm using the jwt crate and I want to set the expiration date in the Claims struct. The exp field in Registered took a Option<u64>.
I can retrieve the current date and add 1 day to it by doing:
let mut timer = time::now();
timer = timer + Duration::days(1);
but I don't see how to convert this time::Tm to a u64.
The exp field is of "NumericDate" type, which according to RFC 7519 is "number of seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date/time, ignoring leap seconds."
This description is the same as the to_timespec method, which "Convert time to the seconds from January 1, 1970" in the Tm's current timezone*.
Thus:
let mut timer = time::now_utc();
timer = timer + Duration::days(1);
token.claims.reg.exp = Some(timer.to_timespec().sec as u64);
(Note that while time + duration always return UTC time as of v0.1.36, it is arguably a defect that could be fixed in a future. To be forward-compatible, I used now_utc() instead of now().)
(*: to_timespec basically calls gmtime() on POSIX and the POSIX standard ignores leap seconds. On Windows it converts the structure to a FILETIME which again ignores leap seconds. So to_timespec is safe to use if you really care about the 27-second difference.)
If you are using std::time::SystemTime, the same can be obtained using
let mut timer = SystemTime::now();
timer += Duration::from_secs(86400);
token.claims.reg.exp = Some(timer.duration_since(UNIX_EPOCH).unwrap().as_secs());

Java TimeZoneOffset time conversion

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;

Getting surprising elapsed time in windows and linux

I have written one function which is platform independent and working nicely in windows as well as linux. I wanted to check the execution time of that function. I am using QueryPerformanceCounter to calculate the execution time in windows and "gettimeofday" in linux.
The problem is in windows the execution time is 60 mili seconds and in linux its showing 4 ms. Its a huge difference b/w them. Can anybody suggest what might went wrong....or If any body knows the some other APIs better than these to calculate elapsed time please let me know...
here is the code for i have written using gettimeofday......
void main()
{
timeval start_time;
timeval end_time;
gettimeofday(&start_time,NULL);
function_invoke(........);
gettimeofday(&end_time,NULL);
timeval res;
timersub(&start_time,&end_time,&res);
cout<<"function_invoke took seconds = "<<res.tv_sec<<endl;
cout<<"function_invoke took microsec = "<<res.tv_usec<<endl;
}
OUTPUT :
function_invoke took seconds = 0
function_invoke took microsec = 4673 ( 4.673 mili seconds )

Resources