0

How can I convert one specific hour, e.g. 18:00, to milliseconds?

I need this so that if it's between for example 12:00 and 18:00 I can do something, and if it is not between 12:00 and 18:00 I can do something else.

I get the current time with:

Private long time;
time = System.currentTimeMillis();

But I don't know how to convert an hour to milliseconds.

I searched on the Internet and it seems that if I use System.currentTimeMillis() it will give me the millisecond of the current day and hour but I need it to update for every day something like this:

Today the time in millis is something like this: 1516994140294. But this number contains this: Fri Jan 26 2018 19:15:40. So if I use the millis for 12:00 and 18:00 of this day this means that tomorrow it will not work as I want.

So can you help me with an example or documentation? Everything can help me :) and thanks in advance.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161

3 Answers3

1

tl;dr

LocalTime.now()                               // Capture current moment. Better to explicitly pass a `ZoneId` object than rely implicitly on the JVM’s current default time zone.
         .isBefore( LocalTime.of( 18 , 0 ) )  // Compare the current time-of-day against the limit.

No need for milliseconds count

No need to count milliseconds. Java has smart date-time classes for this work, found in the java.time package built into Java 8 and later. For earlier Android, see the last bullets below.

No need for System.currentTimeMillis(). The java.time classes do the same job.

LocalTime

To get the current time of day, without a date and without a time zone, use LocalTime.

Determining the current time requires a time zone. For any given moment, the time-of-day varies by zone. If omitted, the JVM’s current default time zone is applied implicitly. Better to explicitly specify your desired/expected time zone, as the default may change at any moment before or during runtime.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalTime now = LocalTime.now( z ) ;

Compare with methods isBefore, isAfter, and equals.

A shorter way of asking "is equal to or later than noon" is "is not before noon".

boolean isAfternoon = 
    ( ! now.isBefore( LocalTime.NOON ) ) 
    && 
    now.isBefore( LocalTime.of( 18 , 0 ) )
;

If you are concerned about the effects of anomalies such as Daylight Saving Time( DST), explore the use of ZonedDateTime instead of mere LocalTime.


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?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0
  1. Split the current time by the ':' delimiter. The first is hours, second is minutes, third is seconds.
  2. Convert the hours to minutes. That is, 18*60.
  3. Add the above answer to the current minutes (18*60 + 00) in this case.
  4. Take the above answer and multiply by 60 for seconds ((18*60 + 00)*60).
  5. Again, take the above, and add your seconds ((18*60 + 00)*60 + 00) in this case.
  6. Again, take the above, multiply by 1000 for milliseconds (((18*60 + 00)*60 + 00)*1000).

Viola, you have your time in milliseconds.

Treyten Carey
  • 641
  • 7
  • 17
0

You should take a look at SimpleDateFormat

There's a good tutorial here

To compare two "dates" you should look at how to create a Calendar (or the more simplified but deprecated Date) object. It implements comparable, so you can convert the current time into a Date object and compare it to known timestamps (like in your question):

Jave Calendar Java Date

You can set both Calendar and Date to a specific time or the current time. For example Calendar.setCurrentTimeMillis(System.currentTimeMillis()) will get a Calendar instance set the current time (just like Calendar.getInstance()).

Here's an example with Date:

    // This is how to get today's date in Java
    Date today = new Date();

    //If you print Date, you will get un formatted output
    System.out.println("Today is : " + today);

    //formatting date in Java using SimpleDateFormat
    SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy");
    String date = DATE_FORMAT.format(today);
    System.out.println("Today in dd-MM-yyyy format : " + date);

    //Another Example of formatting Date in Java using SimpleDateFormat
    DATE_FORMAT = new SimpleDateFormat("dd/MM/yy");
    date = DATE_FORMAT.format(today);
    System.out.println("Today in dd/MM/yy pattern : " + date);

    //formatting Date with time information
    DATE_FORMAT = new SimpleDateFormat("dd-MM-yy:HH:mm:SS");
    date = DATE_FORMAT.format(today);
    System.out.println("Today in dd-MM-yy:HH:mm:SS : " + date);

    //SimpleDateFormat example - Date with timezone information
    DATE_FORMAT = new SimpleDateFormat("dd-MM-yy:HH:mm:SS Z");
    date = DATE_FORMAT.format(today);
    System.out.println("Today in dd-MM-yy:HH:mm:SSZ : " + date);

From this site: http://www.java67.com/2013/01/how-to-format-date-in-java-simpledateformat-example.html#ixzz55Jw9BaXW

Jim
  • 10,172
  • 1
  • 27
  • 36
  • yeah but i need to compare 2 dates.. if i change them to string and compare them it will work? – Luis Fernando Scripcaru Jan 26 '18 at 19:35
  • The title of your question doesn't mention comparison - but I've edited my answer to help make it more clear how to use Date and Calendar for comparison like you ask – Jim Jan 26 '18 at 20:00
  • To compare two dates just subtract they as long and you will get the time diff in milliseconds – from56 Jan 26 '18 at 20:24
  • Thanks but i don't need a calendar I have 2 intervals 12:00 -18:00 for day and 18:00-12:00(next day) for night... because i ant that hen is night my I want that my app to have night style and when is morning to have a morning style :) – Luis Fernando Scripcaru Jan 26 '18 at 20:50
  • Because of issues like timezone changes, daylight savings, etc. you should strongly consider using Calendar .. however, if you want to know if the time is "during the day" you could use Calendar for a time period like 4:00 - 18:00 or something, as long as it is during a single day.. see this post: https://stackoverflow.com/questions/10144072/how-to-format-time-intervals-in-java – Jim Jan 26 '18 at 21:07
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jan 27 '18 at 00:27
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Yes, you can use it on Android. For older Android see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Jan 27 '18 at 10:13