-1

I'm using Linux. In C, when I needed to update the date & time I used the function: settimeofday which got timeval structure.

Is there equivalent in Java ? I have the time in milliseconds (from 1970) and I want to set it (as simple as possible). (I want to avoid the calculation of year/month/day/hour/min/second while using SimpleDataFormat.

Is it possible ?

Thanks

user3668129
  • 4,318
  • 6
  • 45
  • 87

2 Answers2

2

Java can use a long for the time in ms after 1970.

Java 8 can use, what is called a Clock, to fake a time other than the real time. Useful for tests: now(Clock) instead of simply LocalDateTime.now().

AFAIK there is not function to correct the system clock itself, for the entire operating system.

You might look whether time servers might be integrated instead, SNTP, NTP.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • To clarify, if the purpose behind the Question is needing fake date-time values for testing, then explore the `Clock` class. Various static methods produce `Clock` objects with altered behavior, which you can pass as argument to the various other date-time classes. The altered behaviors include returning a [specific fixed (unchanging) moment](https://docs.oracle.com/javase/9/docs/api/java/time/Clock.html#fixed-java.time.Instant-java.time.ZoneId-), returning a true moment except shifted by some amount of time, and returning a true time but incrementing by whole seconds or whole minutes etc. – Basil Bourque Jan 20 '18 at 07:09
1

You may use Calendar as:

public static void main(String[] args) {

   // create a calendar
   Calendar cal = Calendar.getInstance();

   // get the time in milliseconds
   System.out.println("Current time is :" + cal.getTime());

   // set time to 5000 ms after january 1 1970
   cal.setTimeInMillis(5000);

   // print the new time
   System.out.println("After setting Time:  " + cal.getTime());
   }
akhil_mittal
  • 23,309
  • 7
  • 96
  • 95
  • 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 20 '18 at 07:03