How to set time in java?

I am trying to set the time to a date in java. How can i do this? so that I could receive monthly months, etc. from the date of time.

+4
source share
4 answers

Use a new date (0L);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); System.out.println(sdf.format(new Date(0L))); 

Take care of the time zone , because it will change, depending on what you have by default.

UPDATE In java 8 you can use the new java.time library

You have this Instant.EPOCH constant

+5
source

As I understand it, you want to save it only in some variable? So use Date epoch = new Date(0);

+4
source

try it

  Calendar c = new GregorianCalendar(TimeZone.getTimeZone("GMT")); c.setTimeInMillis(0); int day = c.get(Calendar.DATE); int month = c.get(Calendar.MONTH) + 1; int year = c.get(Calendar.YEAR); 
+3
source

TL; DR

 Instant.EPOCH 

Using java.time

The inconvenient old time classes, including Date and Calendar , are now deprecated, replaced by java.time classes. Most of the java.time functions are ported to Android (see below).

To get the Java and Unix epoch link date values ​​in 1970-01-01 , use LocalDate . The LocalDate class represents a date value only without time and without a time zone.

 LocalDate epoch = LocalDate.ofEpochDay( 0L ) ; 

epoch.toString: 1970-01-01

To get the date and time of the same era, use the Instant.EPOCH constant. The Instant class represents a moment on the UTC timeline with a nanosecond resolution (up to nine (9) decimal digits).

 Instant epoch = Instant.EPOCH ; 

epoch.toString (): 1970-01-01T00: 00: 00Z

Z in this ISO 8601 standard, the output does not comply with Zulu and means UTC .

To get several years, months, days since then, use the Period class.

 Period period = Period.between( LocalDate.ofEpochDay( 0 ) , LocalDate.now( ZoneId.of( "America/Montreal" ) ) ) ; 

Search for further discussion and examples of Period .


About java.time

The java.time framework is built into Java 8 and later. These classes supersede the nasty old legacy time classes such as java.util.Date , Calendar and SimpleDateFormat .

The Joda-Time project, now in maintenance mode , we recommend switching to the java.time classes.

To learn more, see the Oracle Tutorial . And search for qaru for many examples and explanations. JSR 310 specification .

Where to get java.time classes?

+1
source

Source: https://habr.com/ru/post/1489712/


All Articles