Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get milliseconds by next Saturday

I am developing a weekly event, but I need to get the milliseconds (unix timestamp) by next Saturday. How can I do that?

like image 385
anzure Avatar asked Dec 09 '25 06:12

anzure


2 Answers

1 create a calendar

 Calendar calNow = Calendar.getInstance();

2 create another calendar, set it to midnight and move day by day until you hit Saturday

    Calendar calNextSat = Calendar.getInstance();
    calNextSat.set(Calendar.HOUR, 0);
    calNextSat.set(Calendar.MINUTE, 0);
    calNextSat.set(Calendar.SECOND, 0);
    while(calNextSat.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY){
        calNextSat.add(Calendar.DATE, 1);
    }

    System.out.println(calNextSat.getTimeInMillis() - calNow.getTimeInMillis());

handle the scenario if it is already Saturday you would get <=0 result

like image 93
jmj Avatar answered Dec 10 '25 20:12

jmj


I am developing a weekly event

Using milliseconds for this kind of date-time tracking will probably lead you astray. For example, because of Daylight Saving Time (DST) and other anomalies, a day is not always 24-hours long and therefore a week is not always ( ( 1000L * 60 * 60 * 24 ) * 7 ) milliseconds long.

Joda-Time or java.time

I suggest learning how to use a sophisticated date-time library. In Java that means either:

  • Joda-Time
  • java.time (built into Java 8, inspired by Joda-Time).

Time Zone

The time zone is crucial in determining the day and day-of-week. Use proper time zone names, never the 3 or 4 letter codes.

Example Code To Get Next Day-Of-Week

Here is example code using Joda-Time 2.7.

Get the time zone you desire/expect. If working in UTC, use the constant DateTimeZone.UTC.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );

Get the date-time value you need. Here I am using the current moment.

DateTime dateTime = DateTime.now( zone );

Specify the future day-of-week you want. Note that Joda-Time uses the sensible # 1 for first day of week, rather than zero-based counting found in java.util.Calendar. First day of week is Monday, per international norms and standards (not Sunday as is common in United States).

int dayOfWeek = DateTimeConstants.SATURDAY;

The withDayOfWeek command may go back in time. So we use a ternary operator (?:) to make sure we go forwards in time by adding a week as needed.

DateTime future = ( dateTime.getDayOfWeek() < dayOfWeek )
        ? dateTime.withDayOfWeek( dayOfWeek )
        : dateTime.plusWeeks( 1 ).withDayOfWeek( dayOfWeek );

You may want to adjust the time-of-day to the first moment of the day to emphasize the focus on the day rather than a particular moment within the day.

future = future.withTimeAtStartOfDay(); // Adjust time-of-day to first moment of the day to stress the focus on the entire day rather than a specific moment within the day. Or use `LocalDate` class.

Dump to console.

System.out.println( "Next day # " + dayOfWeek + " after " + dateTime + " is " + future );

When run.

Next day # 6 after 2015-04-18T16:03:36.146-04:00 is 2015-04-25T00:00:00.000-04:00

Until Then

The code above gives us the desired future point in time (next Saturday).

If all you really want is the number of milliseconds between now and then, subtract between each one’s internal count-from-epoch in milliseconds. Note the use of 64-bit long rather than 32-bit int when tracking times as milliseconds.

long elapsedMilliseconds = ( future.getMillis() - dateTime.getMillis() );

Note that if you are doing this work in java.time rather Joda-Time, be aware that internally java.time uses nanoseconds rather than milliseconds. You can find milliseconds-savvy methods as I recall. Or divide nanoseconds by a million (yes, million not thousand, as microseconds are in between.

You may want to more intelligently represent the span of time between now and then. Joad-Time offers three classes for representing a span of time in various manners:

  • Interval (a pair of fixed points on the time line)
  • Period (a number of months, days, hours, and such)
  • Duration (a number of milliseconds).

Example code, again Joda-Time 2.7.

Interval interval = new Interval( dateTime , future );
Period period = interval.toPeriod();

Dump to console.

System.out.println( "interval: " + interval );
System.out.println( "period: " + period );

When run.

interval: 2015-04-18T16:17:45.109-04:00/2015-04-25T00:00:00.000-04:00
period: P6DT7H42M14.891S

Notice the String representation format used by default for the Period value. That format is standard, part of ISO 8601, called a duration in their terminology. That format is PnYnMnDTnHnMnS where the P marks the beginning and the T separates the date portion from the time portion.

Both Joda-Time and java.time use ISO 8601 as their defaults in both parsing and generating string representations of date-time values.

like image 25
Basil Bourque Avatar answered Dec 10 '25 18:12

Basil Bourque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!