I have the test start time (say 9:05:30) and total duration (say 5000 seconds) that a test should run.How to calculate the end time from start time and end time?
If you're using something like Instant, ZonedDateTime or LocalDateTime from the Java 8 time API, you can use plusSeconds:
Instant startTime = ...
Instant endTime = startTime.plusSeconds(5000);
If you're using Date (oh, the horrors...), you can simply use getTime:
Date startTime = ...
Date endTime = new Date(startTime.getTime() + TimeUnit.SECONDS.toMillis(5000));
In javascipt you can do
console.time('testSomeCall');
//code here
console.timeEnd('testSomeCall');
in other languages usually you get the time or timestamp before your test and then after and do end - init, like this in this for java
long timeInit = System.currentTimeMillis();
//some code here
long timeEnd = System.currentTimeMillis();
System.out.println("Ttotal time: " + (timeEnd - timeInit));
String myTime = "9:05:20";
// before calculation
Date tempStartTime = new SimpleDateFormat("HH:mm:ss").parse(myTime);
int hours = tempStartTime.getHours();
int minutes = tempStartTime.getMinutes();
int seconds = tempStartTime.getSeconds();
int elapsedSeconds = 5000;
// add seconds
int totalSeconds = seconds + elapsedSeconds;
// after calculation
Date tempEndTime = new SimpleDateFormat("HH:mm:ss").parse(hours + ":" + minutes + ":" + totalSeconds);
hours = tempEndTime.getHours();
minutes = tempEndTime.getMinutes();
seconds = tempEndTime.getSeconds();
System.out.println(hours + ":" + minutes + ":" + seconds);
// Output is 10:28:40
How can 09:05:5020 be parsed as Date?
the value is successfully parsed as the 5020th seconds, simply rolling over to next minute after each 60 seconds to accommodate the Out-Of-Bounds value. If you want to prevent this, call setLenient(false); on a DateFormat object before parsing (leniency is true by default).
The Answer by Andy Turner is correct about using java.time rather than the old date-time classes. Here's more specific detail.
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
Instant
If just programmatically getting 5,000 seconds later from now, use the Instant object as shown in Turner’s Answer. An Instant is a moment on the timeline in UTC with a resolution up to nanoseconds.
Instant later = Instant.now().plusSeconds( 5_000 );
LocalTime
The LocalTime class represents a time-of-day without a date and without a time zone. So this works only for generic 24-hour days, not realistic days with time zones that have anomalies such as Daylight Saving Time (DST).
LocalTime lt = LocalTime.parse( "09:05:30" );
LocalTime later = lt.plusSeconds( 5_000 );
If hitting midnight, the result will roll-over into the early hours of the day starting with hour 00, then 01, and so on.
ZonedDateTime
If you want a realistic value that respects DST and so on, use ZonedDateTime.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate tomorrow = LocalDate.now( zoneId ).plusDays( 1 );
LocalTime lt = LocalTime.parse( "09:05:30" );
ZonedDateTime tomorrowAround9Am = ZonedDateTime.of( tomorrow , lt , zoneId 0;
ZonedDateTime later = tomorrowAround9Am.plusSeconds( 5_000 );
Related
I want to be able to bypass this code (getTimeInMillis() in Calendar class) and simply return the zero hour, minutes, and seconds from a specific date. Time is not set because it was built as a "Date" only now. So right now my code is always hitting this and giving me an "offset." This is even after doing below:
this.getEventDate().set(Calendar.HOUR_OF_DAY, 0);
I want to return milliseconds as long. Right now it uses Calendar.getTimeInMillis() which calculates a time as its not originally on the date object.
Is there a method out there to handle this?
public static long millisSinceStartOfToday() {
Calendar date = new GregorianCalendar();
// reset hour, minutes, seconds and millis
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
return (new Date().getTime() - date.getTime().getTime());
}
Your Question could use a rewrite for clarity. But I’ll take a guess at what you are asking.
Avoid legacy date-time classes
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
First moment of the day
You seem to be asking to determine the first moment of the day.
Understand that some dates in some time zones do not start at 00:00:00. So let java.time determine the first moment.
Here is an example. In Iran, the day of “Spring Ahead” in Daylight Saving Time starts at the stroke of midnight. The clock jumps to 1 AM. So the hour of 00:00:00 does not exist.
ZoneId z = ZoneId.of( "Asia/Tehran" ) ;
LocalDate ld = LocalDate.of( 2022 , Month.MARCH, 22 ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
See this code run live at IdeOne.com.
2022-03-22T01:00+04:30[Asia/Tehran]
Count of milliseconds
And you apparently want to get a count of milliseconds from the epoch reference of first moment of 1970 as seen in UTC, an offset of zero hours-minutes-seconds.
Instant instant = zdt.toInstant() ; // Adjust from time zone to UTC by extracting an `Instant`.
long millis = instant.toEpochMilli() ;
1647894600000
If you want to get the number of milliseconds from a specified time to 00:00:00 of the day, the following code may help you
final long now = System.currentTimeMillis();
final long DAY_MILLIS = 1000 * 60 * 60 * 24;
//`now - (now % DAY_MILLIS)` will get the mill second at 08:00
long dayStart = now - (now % DAY_MILLIS) - DAY_MILLIS / 3;
long millisSinceStartOfToday = now - dayStart;
//in other word
//millisSinceStartOfToday = (now % DAY_MILLIS) + DAY_MILLIS / 3;
I had a timestamp in Unix with milliseconds, now I need the start of the day and end of the day with milliseconds for the same given timestamp.
Eg: 1637293359000 - Given timestamp
Start of the day to be 1637280000000
End of the day to be 1637323199000
In System default timezone you could try like this
ZoneId zoneId = ZoneId.systemDefault();
long timestamp = 1637293359000L;
LocalDate date = Instant.ofEpochMilli(timestamp).atZone(zoneId).toLocalDate();
LocalDateTime startDay = date.atStartOfDay();
LocalDateTime endDay = date.atTime(LocalTime.MAX);
System.out.println(startDay);
System.out.println(endDay);
long startDayLongValue = startDay.atZone(zoneId).toInstant().toEpochMilli();
long endDayLongValue = endDay.atZone(zoneId).toInstant().toEpochMilli();
System.out.println(startDayLongValue);
System.out.println(endDayLongValue);
We can achieve this using DateTime
import org.joda.time.DateTime;
long timestamp = 1629454215381L;
DateTime dateTime=new DateTime(timestamp );
long StartOfDayMillis = dateTime.withMillis(System.currentTimeMillis()).withTimeAtStartOfDay().getMillis();
long EndOfDayMillis = dateTime.withMillis(StartOfDayMillis).plusDays(1).minusSeconds(1).getMillis();
tl;dr
Here is the complete code to a record representing the day of a specified moment as seen in a particular time zone. A static factory method contains our logic.
package work.basil.example;
import java.time.*;
import java.util.Objects;
public record DayInMillis( long start , long end )
{
public static DayInMillis from ( final long countOfMillisSinceEpoch , final ZoneId zoneId )
{
Objects.requireNonNull( zoneId );
Instant instant = Instant.ofEpochMilli( countOfMillisSinceEpoch );
ZonedDateTime zdt = instant.atZone( zoneId );
LocalDate ld = zdt.toLocalDate();
ZonedDateTime start = ld.atStartOfDay( zoneId );
ZonedDateTime end = ld.plusDays( 1 ).atStartOfDay( zoneId );
Instant startInstant = start.toInstant();
Instant endInstant = end.toInstant();
long startMilli = startInstant.toEpochMilli();
long endMilli = endInstant.toEpochMilli();
System.out.println( "instant = " + instant );
System.out.println( "zdt = " + zdt );
System.out.println( "start/end = " + start + "/" + end );
System.out.println( "startInstant/endInstant = " + startInstant + "/" + endInstant );
System.out.println( "startMilli/endMilli = " + startMilli + "/" + endMilli );
System.out.println( "Duration (not necessarily 24 hours): " + Duration.between( startInstant , endInstant ) );
return new DayInMillis( startMilli , endMilli );
}
}
Example usage:
DayInMillis.from( 1_637_293_359_000L , ZoneId.of( "Asia/Tokyo" ) )
When run.
instant = 2021-11-19T03:42:39Z
zdt = 2021-11-19T12:42:39+09:00[Asia/Tokyo]
start/end = 2021-11-19T00:00+09:00[Asia/Tokyo]/2021-11-20T00:00+09:00[Asia/Tokyo]
startInstant/endInstant = 2021-11-18T15:00:00Z/2021-11-19T15:00:00Z
startMilli/endMilli = 1637247600000/1637334000000
Duration (not necessarily 24 hours): PT24H
dayInMillis = DayInMillis[start=1637247600000, end=1637334000000]
Parse count of seconds
Parse your input count of milliseconds since epoch of first moment of 1970 in UTC as a Instant object.
Instant instant = Instant.ofEpochMilli( 1_637_293_359_000L ) ;
Adjust into time zone
Specify the time zone by which you want to perceive dates.
ZoneId z = ZoneId.of( "America/Edmonton" ) ;
Adjust from UTC (an offset of zero hours-minutes-seconds) to that time zone.
ZonedDateTime zdt = instant.atZone( z ) ;
Get the date
Extract the date-only portion.
LocalDate ld = zdt.toLocalDate() ;
Start of day
Let java.time determine the first moment of the day. Never assume the day starts at 00:00. Some dates in some zones may start at another time such as 01:00.
ZonedDateTime start = ld.atStartOfDay( z ) ;
Half-Open
The last moment of the day is infinitely divisible. For this and other reasons, spans of time are usually best defined using Half-Open approach. In Half-Open, the beginning is inclusive while the ending is exclusive. This means the span of a day starts at the first moment of the day and runs up to, but does not include, the first moment of the following day.
ZonedDateTime end = ld.plusDays( 1 ).atStartOfDay( z ) ;
Now we have the span covered by a pair of ZonedDateTime objects. But you want to get a count of milliseconds since epoch for both of those.
Tracking count-from-epoch is awkward
Let me say, I do not recommend using a count-since-epoch for time-keeping. The values are inherently ambiguous as to both epoch and granularity. Furthermore, using such counts makes debugging difficult and errors hard to spot, as such values are meaningless to human readers.
ISO 8601
Instead, I suggest communicating such values textually in standard ISO 8601 format. The java.time classes use ISO 8601 formats by default when parsing/generating text.
String outputStart = start.toInstant().toString();
String outputEnd = end.toInstant().toString();
Milliseconds since epoch
But if you insist on the count of milliseconds, first extract Instant objects from our ZonedDateTime objects, effectively adjusting to UTC (offset of zero).
Instant startInstant = start.toInstant() ;
Instant endInstant = end.toInstant() ;
Interrogate for a count of milliseconds since epoch.
long startMilli = startInstant.toEpochMilli() ;
long endMilli = endInstant.toEpochMilli() ;
Avoid LocalDateTime for this problem
Notice that at no point did we use the LocalDateTime class. That class purposely lacks the context of a time zone or offset-from-UTC. So LocalDateTime cannot represent a moment, is not a point on the timeline. That makes LocalDateTime irrelevant to the problem at hand.
Tip: ThreeTen-Extra library
If you routinely work with pairs of moments, considering adding the ThreeTen-Extra library to your project. This provides the Interval class for representing a pair of Instant objects. The class carries several handy comparison methods such as abuts, overlaps, contains, and so on.
as a part of my requirement,I have to fire a SQL query which takes yesterday's midnight and today's midnight in the respective time zone as input.Is there a way to achieve this?
Use ZonedDateTime:
String DATE_FORMAT = "dd-M-yyyy hh:mm:ss a";
String dateInString = "22-1-2015 10:15:55 AM";
LocalDateTime ldt = LocalDateTime.parse(dateInString, DateTimeFormatter.ofPattern(DATE_FORMAT));
ZoneId singaporeZoneId = ZoneId.of("Asia/Singapore");
System.out.println("TimeZone : " + singaporeZoneId);
//LocalDateTime + ZoneId = ZonedDateTime
ZonedDateTime asiaZonedDateTime = ldt.atZone(singaporeZoneId);
System.out.println("Date (Singapore) : " + asiaZonedDateTime);
ZoneId newYokZoneId = ZoneId.of("America/New_York");
System.out.println("TimeZone : " + newYokZoneId);
ZonedDateTime nyDateTime = asiaZonedDateTime.withZoneSameInstant(newYokZoneId);
System.out.println("Date (New York) : " + nyDateTime);
DateTimeFormatter format = DateTimeFormatter.ofPattern(DATE_FORMAT);
System.out.println("\n---DateTimeFormatter---");
System.out.println("Date (Singapore) : " + format.format(asiaZonedDateTime));
System.out.println("Date (New York) : " + format.format(nyDateTime));
Output is:
TimeZone : Asia/Singapore
Date (Singapore) : 2015-01-22T10:15:55+08:00[Asia/Singapore]
TimeZone : America/New_York
Date (New York) : 2015-01-21T21:15:55-05:00[America/New_York]
---DateTimeFormatter---
Date (Singapore) : 22-1-2015 10:15:55 AM
Date (New York) : 21-1-2015 09:15:55 PM
Use the methods from here to get what you need
Example taken from: Java – Convert date and time between timezone
simply run your cronjob at every hour and generate only the reports in which timezones the day just ended
java.time
Use a driver compliant with JDBC 4.2 or later, running on Java 8 or later, to benefit from use of the modern java.time classes that supplant the troublesome old legacy date-time classes.
Determining "today" and "yesterday" means determining a date. Determining a date requires a time zone. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
LocalDate yesterday = today.minusDays( 1 ) ;
To query for timestamps in the database, we need specific moments. The Question specifies midnight. The term "midnight" is vague. Let's use "first moment of the day" instead.
Never assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) mean it may start at another time such as 01:00:00. Let java.time determine first moment of the day.
ZonedDateTime start = yesterday.atStartOfDay( z ) ;
Generally, the best approach to defining a span of time is though the Half-Open approach where the beginning is inclusive while the ending is exclusive. So we want to start at first moment of one day and run up to, but not include, the first moment of the next day.
ZonedDateTime stop = today.atStartOfDay( z ) ;
In Half-Open, we do not use the SQL command BETWEEN.
SQL
SELECT * FROM t
WHERE event >= ? AND event < ? ;
Java
myPreparedStatement.setObject( 1 , start ) ;
myPreparedStatement.setObject( 2 , stop ) ;
To retrieve the timestamps, use getObject.
Instant instant = myResultSet.getObject( "event" , Instant.class ) ;
To move from UTC to a zone, apply a ZoneId.
ZonedDateTime zdt = instant.atZone( z ) ;
I have a code of which is used to create a 24 hour countdown.
This code checks if a "date" file exists and if it doesn't it creates one, which contains the date and time in 24 hourse/a day. It then gets the current time and compares the two, to create a countdown from the current date, to the date in the document.
This makes it possible to save the timer and check how far it has come even though the code is "turned off". The only issue is the fact that sometimes the timer turns negative. Like if I run the code from the start with no "date" file created on Monday, right before midnight, lets say Monday at half past eleven at night. Then if I stop the code and run it again when the current date has passed midnight, so it is actually Tuesday, but there is still missing up to 23 hours before it hits the actual goal timer. If this is the case, the time left in the countdown is negative. Like it would show "-1day 23hours 60minutes and 60seconds remaining". But if as an example it is run from scratch past midnight on Tuesday and then relaunch after 30 minutes the same day, there is no issue.
I hope you can understand what the issue is, it is slightly hard to express through text. But I have attached the whole code of mine, which is the exact one I am using and of which is having that issue. The code has comments for every actions happening, so it should be rather easy to understand.
static File dFileD = new File("date.txt");
static String date = "";
public static void main(String[] args) throws ParseException {
Timer tickTock = new Timer();
TimerTask tickTockTask = new TimerTask(){
public void run(){
try {
timFunRun(); //Timer calls method to start the countdown
} catch (ParseException e) {
e.printStackTrace();
}
}
};
tickTock.schedule(tickTockTask, 1000, 1000);
}
static void timFunRun() throws ParseException {
if (!dFileD.exists()){ //if it doesn't exist, first part
//Get current date and time
Calendar startDat = Calendar.getInstance();
System.out.println("Current date: " + startDat.getTime());
//Get that current date and time and then add 1 day
Calendar todAdd = Calendar.getInstance();
todAdd.add(Calendar.DATE, 1);
System.out.println("Date in 1 day: " + todAdd.getTime());
//Create a format for sending date to text file
SimpleDateFormat formDat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
String formatted = formDat.format(todAdd.getTime());
System.out.println("Formatted: " + formatted);
try{
PrintWriter dW = new PrintWriter("date.txt");
dW.println(formatted);
dW.close();
} catch (IOException e) {
}
System.out.println(formDat.parse(formatted));
} else { //if it does exist, second part
//Get current date and time
Calendar currentDeT = Calendar.getInstance();
System.out.println("Current date: " + currentDeT.getTime());
SimpleDateFormat formDat2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
Date dateFroText = null; //Get the "goal" date
try {
Scanner dateRead = new Scanner(dFileD);
while (dateRead.hasNextLine()) {
date = dateRead.nextLine();
dateFroText = formDat2.parse(date);
System.out.println("Date from text new format: " + dateFroText);
}
dateRead.close();
} catch (Exception e) {
System.out.println("Error!");
}
if (dateFroText != null){ //method to compare the current date and the goal date
Calendar dateFromTxtCal = Calendar.getInstance();
dateFromTxtCal.setTime(dateFroText);
int yearDiff = dateFromTxtCal.get(Calendar.YEAR) - currentDeT.get(Calendar.YEAR);
int dayDiff = ((yearDiff*365) + dateFromTxtCal.get(Calendar.DAY_OF_YEAR)) - currentDeT.get(Calendar.DAY_OF_YEAR);
dayDiff--;
int hourDiffer = dateFromTxtCal.get(Calendar.HOUR_OF_DAY)+23 - currentDeT.get(Calendar.HOUR_OF_DAY);
int minuDiff = dateFromTxtCal.get(Calendar.MINUTE)+60 - currentDeT.get(Calendar.MINUTE);
int secoDiff = dateFromTxtCal.get(Calendar.SECOND)+60 - currentDeT.get(Calendar.SECOND);
System.out.println(dayDiff + " days " + hourDiffer + " hours " + minuDiff +" minutes " + secoDiff + "seconds remaining");
}
}
}
Avoid legacy date-time classe
You are working too hard. And you are using troublesome old date-time classes now obsoleted and supplanted by the java.time classes.
Work in UTC
Also, if you only care about the next 24 hours, then no need for time zones. Just use UTC.
Instant
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instantNow = Instant.now();
Duration
A span of time unattached to the timeline is represented by the Duration or Period classes.
Duration duration = Duration.ofHours( 24 );
You can perform date-time math, adding a Duration to an Instant. The java.time classes use immutable objects, so the result of such manipulations is a fresh object with values based on the original.
Instant instantLater = instantNow.plus( duration );
ISO 8601
To serialize date-time values such as those to text, use the standard ISO 8601 formats. The java.time classes use ISO 8601 by default when generating and parsing strings.
String output = instantNow.toString();
2017-04-03T03:18:48.183Z
Calculate remaining time
To get the remaining time, let java.time do the math.
Duration remaining = Duration.between( Instant.now() , instantLater );
To report that in standard ISO 8601 format, call toString. The format for durations is PnYnMnDTnHnMnS. The P marks the beginning (for Period), and the T separates any years-months-dates from hours-minutes-seconds.
String outputRemaining = remaining.toString();
PT23H34M22S
To generate a longer string, in Java 9 call the to…Part method for each unit (hours, minutes, seconds). Oddly those methods were omitted from the original java.time.Duration class in Java 8. You could look to the source code of Java 9 to write similar code.
Or more simply, manipulate the standard string. Delete the PT. Replace the H with hours and so on. Do S first to avoid the plural s in the other two words. Admittedly this is kind of a hack, but it works thanks to some good luck in the occurrence of letters is the English spelling of hours-minutes-seconds.
String output = remaining.toString()
.replace( "PT" , "" )
.replace( "S" , " seconds " )
.replace( "H" , " hours " )
.replace( "M" , " minutes " ) ;
23 hours 34 minutes 22 seconds
ZonedDateTime
If you want to display the target date-time in the user's desired/expected time zone, apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
To generate a string in standard format, call toString. Actually the ZonedDateTime class extends the standard by appending the name of the time zone in square brackets.
To generate strings in other formats, search Stack Overflow for many examples of DateTimeFormatter class.
Converting to java.util.Date
The Timer class has not yet been updated to work with the java.time types. So convert back to a Date object via new methods added to the old classes, in this case from.
java.util.Date date = java.util.Date.from( instantLater );
Or use a count of milliseconds from the Duration object.
long milliseconds = duration.toMillis() ;
ScheduledExecutorService
FYI, the Timer and TimeTask classes have been supplanted by the Executors framework. Specifically for your purpose, the ScheduledExecutorService. Search Stack Overflow for many examples and discussions.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I want to get the time of a day in milliseconds, I do not this day to have any specific date, just a time. I made something, thought it worked, but then went debugging and concluded that it doesn't work how I want it to.
I want to use this to check if the current time is between both my specified startTime and endTime.
long startTime = settings.getLong("startTime", 0);
long endTime = settings.getLong("endTime", 0);
if ((currentTime.getMillis() >= startTime)
&& (currentTime.getMillis() <= endTime)) {
//Do stuff here
}
How I am setting the time of the propeties startTime and endTime:
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, 16);
startTime.set(Calendar.MINUTE, 00);
editor.putLong("startTime",
startTime.getTimeInMillis());
Calendar endTime = Calendar.getInstance();
endTime.set(Calendar.HOUR_OF_DAY, 16);
endTime.set(Calendar.MINUTE, 00);
endTime.add(Calendar.HOUR_OF_DAY, 11);
editor.putLong("endTime",
endTime.getTimeInMillis());
editor.commit();
However this will mean that both startTimeand endTime will have this a specific date attached to it.
I hope I explained it well, any help is appreciated!
Avoid Milliseconds
No need to mess with milliseconds for your purpose. Using milliseconds for date-time is confusing and error-prone.
What you need is a decent date-time library rather than the notoriously troublesome bundled java.util.Date & .Calendar classes.
Joda-Time
If you are certain you want to ignore dates and ignore time zones, here's some example code using the LocalTime class offered by the third-party free-of-cost Joda-Time library.
LocalTime start = new LocalTime( 10, 0, 0 );
LocalTime stop = new LocalTime( 14, 30, 0 );
LocalTime target = LocalTime.now();
boolean isNowInSpan = !( ( target.isBefore( target ) ) | ( target.isAfter( stop ) ) );
Adjust that last line according to your business logic needs. You might want:
The beginning and ending are inclusive
The beginning and ending are exclusive
"Half-Open" where the beginning is inclusive and the ending is exclusive(usually best for date-time work)
Dump to console…
System.out.println( "start: " + start );
System.out.println( "stop: " + stop );
System.out.println( "target: " + target );
System.out.println( "isNowInSpan: " + isNowInSpan );
When run…
start: 10:00:00.000
stop: 14:30:00.000
target: 23:49:37.779
isNowInSpan: false
Another Example
Time-of-day-only is not usually the right way to go. When new to date-time work, a naïve programmer may at first think that time-only simplifies things. On the contrary, this example shows how spinning around the clock creates complications. Using date+time+timeZone is usually the best approach in the long run.
LocalTime now = LocalTime.now();
LocalTime start = new LocalTime( 13, 0, 0, 0 );
LocalTime stop = start.plusHours( 11 );
System.out.println( "now: " + now );
System.out.println( "start: " + start );
System.out.println( "stop: " + stop );
if ( now.isAfter( start ) ) {
System.out.println( "After start" );
}
if ( now.isBefore( stop ) ) {
System.out.println( "Before stop" );
}
When run…
now: 14:00:32.496
start: 13:00:00.000
stop: 00:00:00.000
After start
java.time
Java 8 brings the new java.time package, inspired by Joda-Time, defined by JSR 310.
In java.time, you will find a LocalTime class similar to the one in Joda-Time.
A new approach with Java 8 onward.
int millisecondsOfDay = LocalTime.now().get(ChronoField.MILLI_OF_DAY);
Reference: https://o7planning.org/13669/java-localtime#a64448233
Take a look at the Java 8 Time API.
http://download.java.net/jdk8/docs/api/java/time/LocalTime.html#toNanoOfDay--
Time without Date is meaning less. In Java timestamp it's using the Unix UTC and the timestamp start 0 on 01/01/1970. So, you startTime/endTime.getTimeInMillis() tell you the time different from UTC. Which mean your midnight is your base and your endTime.getTimeInMillis() will be the offset.
Calendar cal = Calendar.getInstance();
// set to mid-night
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long midnight = cal.getTimeInMillis();
cal.set(Calendar.HOUR_OF_DAY, 16);
cal.set(Calendar.MINUTE, 00);
long startTime = cal.getTimeInMillis();
editor.putLong("startTime", (startTime - midnight));
cal.add(Calendar.HOUR_OF_DAY, 11);
long endTime = cal.getTimeInMillis();
editor.putLong("endTime", (endTime - midnight));
editor.commit();
java.time.LocalTime
I recommend that you use java.time, the modern Java date and time API, for your time work. Use a LocalTime object for time of day (it’s what it’s for).
LocalTime time = LocalTime.of(16, 0);
System.out.println(time);
Output:
16:00
If you cannot store a LocalTime object in your settings, convert to a string for human readability (a great advantage in debugging and support cases):
String timeString = time.toString();
LocalTime parsedBack = LocalTime.parse(timeString);
System.out.println(parsedBack);
16:00
To answer the question as asked, in case you need to, converting to milliseconds is straightforward (when you know how):
int milliOfDay = time.get(ChronoField.MILLI_OF_DAY);
System.out.println(milliOfDay);
57600000
The milliseconds too can be converted back to a LocalTime object:
LocalTime recreatedLocalTime
= LocalTime.MIN.with(ChronoField.MILLI_OF_DAY, milliOfDay);
System.out.println(recreatedLocalTime);
16:00
Link
Oracle tutorial: Date Time explaining how to use java.time.
In case what you need is to get how many milliseconds since the start of this day and you have now in milliseconds you can get the milliseconds you want as simple as this
val nowMilliSeconds = System.currentTimeMillis() % 86400000
Where 86400000 is the number of milliseconds in a day so you will just get the remainder