System currenttimemillis java что возвращает
Перейти к содержимому

System currenttimemillis java что возвращает

  • автор:

System currenttimemillis java что возвращает

That will print a human readable time in your local timezone.

To understand exactly what System.currentTimeMills() returns we must first understand: what UTC is, what UNIX timestamps are and how they form a universal time keeping standard.

Greenwich Meridian / Prime Meridian (0 degrees longitude)

The current UTC date/time is . Your local time is

A UNIX timestamp, also known as Epoch Time or POSIX timestamp, is a representation of a moment defined as the time that has elapsed since a reference known as the UNIX epoch: 1970-01-01 00:00:00 UTC (what is UTC). Using Java as an example, System.currentTimeMillis() returns just that, a UNIX timestamp in milliseconds — UNIX timestamps will often be measured in seconds as well (but System.currentTimeMillis() will always be in milliseconds). Following is a table that unifies these concepts:

Note that System.currentTimeMillis() is based on the time of the system / machine it’s running on.

In conclusion, the UNIX timestamp is just a system / format for representing a moment in time.
Check out some other date / time systems.

UTC, timezones, offsets & milliseconds since the Unix epoch

The ‘snapshot’ above represents the same moment from 4 different perspectives: John’s timezone, Juliette’s timezone, UTC (Coordinated Universal Time) and milliseconds from the Unix epoch.

Java’s Calendar (and deprecated Date ) itself stores time as milliseconds since the Unix Epoch. This is great for many reasons. It happens not only in Java but in other programming languages as well. In my experience i found the perfect time-keeping architecture emerges naturally from this: the Unix Epoch is January 1st, 1970, midnight, UTC. Therefore if you choose to store time as milliseconds since the Unix Epoch you have a lot of benefits:

  • architecture clarity: server side works with UTC, client side shows the time through its local timezone
  • database simplicity: you store a number (milliseconds) rather than complex data structures like DateTimes
  • programming efficiency: in most programming languages you have date/time objects capable of taking milliseconds since Epoch when constructed (which allows for automatic conversion to client-side timezone)

Database stores timestamp as a number, server works in UTC, client displays time in local timezone

What might happen above is that the sorting for such a small array could be so fast that the duration shows up as zero. For this you can use the trick of repeating the method call multiple times so that you get more relevant durations & comparisons:

The easiest way to manually deduce when the method started would be to convert 2015-03-15 10:13:32:564 into milliseconds, subtract 3367, then convert back to a time. The starting point of the activity is relevant because other activities that ran in parallel can be investigated. It’s important to note though that a line such as the one above is normally indicative of poor logging because if the starting point is relevant it can be calculated programmatically (and printed) at the moment of logging.

are used to cushion & spread a delay over a time period. For example: Leap seconds are one-second adjustments added to the UTC time to synchronize it with solar time. Leap seconds tend to cause trouble with software. For example, on June 30, 2012 you had the time 23:59:60. Google uses a technique called leap smear on its servers, which, instead of adding an extra second, extends seconds prior to the end of the day by a few milliseconds each so that the day will last 1000 milliseconds longer. A different but related programming challenge is to keep timestamps in the database in an ascending order during leap seconds. Below is a pseudocode solution involving a technique similar to the ‘smear’:

System.currentTimeMillis() offers precision to the millisecond but its accuracy still depends on the underlying machine. This is why, in some cases, it might happen that two subsequent calls can return the same number even if they are in fact more than 1ms apart. The same is true about nanoTime() : precision is down to the nanosecond but accuracy doesn’t follow, it still depends on the machine.

System.nanoTime() , however, returning nanoseconds, may arguably be better suited to measure deltas (although reportedly a nanoTime() call can be slower than a currentTimeMillis() call — my experiments contradict this: they seem to take exactly the same amount of time). nanoTime() ‘s disadvantage is it doesn’t have a fixed reference point like currentTimeMillis() has the Unix epoch. nanoTime() ‘s reference might change with a system/machine restart, so from the mentioned methods currentTimeMillis() is the one to use for time-keeping.

UTC stands for Coordinated Universal Time. GMT stands for Greenwich Mean Time. UTC is a universal time keeping standard by itself and a GMT successor. A time expressed in UTC is essentially the time on the whole planet. A time expressed in GMT is the time in the timezone of the Greenwich meridian. In current computer science problems (and probably most scientific ones) UTC and GMT expressed in absolute value happen to have identical values so they have been used interchangeably.

A detailed analysis reveals that literature and history here are a bit ambiguous. UTC essentially appeared in 1960, GMT being the ‘main thing’ until then. Unlike GMT which is based on solar time and originally calculated a second as a fraction of the time it takes for the Earth to make a full rotation around its axis, UTC calculates a second as “the duration of 9192631770 periods of the radiation corresponding to the transition between the two hyperfine levels of the ground state of the cesium 133 atom”. UTC’s second is far more precise than GMT’s original second. In 1972 leap seconds were introduced to synchronize UTC time with solar time. These 2 turning points (different definition of a second and the introduction of leap seconds) ‘forced’ GMT to be the same as UTC based on what seemed a gradual, tacit convention. If you were to calculate true GMT today i would see it based on its original definition of 1 second = 1/86400 days and this would for sure return a different absolute value than what UTC gives us. From this point of view the name “GMT” seems deprecated, but kept around for backward compatibility, traditional timezone based representation of time and sometimes legal reasons.

Class System

For simple stand-alone Java applications, a typical way to write a line of output data is:

See the println methods in class PrintStream .

Typically this stream corresponds to display output or another output destination specified by the host environment or user. By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out , has been redirected to a file or other destination that is typically not continuously monitored.

Method Details

setIn

setOut

setErr

console

inheritedChannel

In addition to the network-oriented channels described in inheritedChannel , this method may return other kinds of channels in the future.

setSecurityManager

Otherwise, the argument is established as the current security manager. If the argument is null and no security manager has been established, then no action is taken and the method simply returns.

getSecurityManager

currentTimeMillis

See the description of the class Date for a discussion of slight discrepancies that may arise between «computer time» and coordinated universal time (UTC).

nanoTime

This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) — no guarantees are made except that the resolution is at least as good as that of currentTimeMillis() .

Differences in successive calls that span greater than approximately 292 years (2 63 nanoseconds) will not correctly compute elapsed time due to numerical overflow.

The values returned by this method become meaningful only when the difference between two such values, obtained within the same instance of a Java virtual machine, is computed.

For example, to measure how long some code takes to execute:

To compare elapsed time against a timeout, use instead of because of the possibility of numerical overflow.

arraycopy

If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array.

If dest is null , then a NullPointerException is thrown.

If src is null , then a NullPointerException is thrown and the destination array is not modified.

  • The src argument refers to an object that is not an array.
  • The dest argument refers to an object that is not an array.
  • The src argument and dest argument refer to arrays whose component types are different primitive types.
  • The src argument refers to an array with a primitive component type and the dest argument refers to an array with a reference component type.
  • The src argument refers to an array with a reference component type and the dest argument refers to an array with a primitive component type.
  • The srcPos argument is negative.
  • The destPos argument is negative.
  • The length argument is negative.
  • srcPos+length is greater than src.length , the length of the source array.
  • destPos+length is greater than dest.length , the length of the destination array.

Otherwise, if any actual component of the source array from position srcPos through srcPos+length-1 cannot be converted to the component type of the destination array by assignment conversion, an ArrayStoreException is thrown. In this case, let k be the smallest nonnegative integer less than length such that src[srcPos+ k ] cannot be converted to the component type of the destination array; when the exception is thrown, source array components from positions srcPos through srcPos+ k -1 will already have been copied to destination array positions destPos through destPos+ k -1 and no other positions of the destination array will have been modified. (Because of the restrictions already itemized, this paragraph effectively applies only to the situation where both arrays have component types that are reference types.)

identityHashCode

getProperties

The current set of system properties for use by the getProperty(String) method is returned as a Properties object. If there is no current set of system properties, a set of system properties is first created and initialized. This set of system properties includes a value for each of the following keys unless the description of the associated value indicates that the value is optional.

Shows property keys and associated values

Key Description of Associated Value
java.version Java Runtime Environment version, which may be interpreted as a Runtime.Version
java.version.date Java Runtime Environment version date, in ISO-8601 YYYY-MM-DD format, which may be interpreted as a LocalDate
java.vendor Java Runtime Environment vendor
java.vendor.url Java vendor URL
java.vendor.version Java vendor version (optional)
java.home Java installation directory
java.vm.specification.version Java Virtual Machine specification version, whose value is the feature element of the runtime version
java.vm.specification.vendor Java Virtual Machine specification vendor
java.vm.specification.name Java Virtual Machine specification name
java.vm.version Java Virtual Machine implementation version which may be interpreted as a Runtime.Version
java.vm.vendor Java Virtual Machine implementation vendor
java.vm.name Java Virtual Machine implementation name
java.specification.version Java Runtime Environment specification version, whose value is the feature element of the runtime version
java.specification.vendor Java Runtime Environment specification vendor
java.specification.name Java Runtime Environment specification name
java.class.version Java class format version number
java.class.path Java class path (refer to ClassLoader.getSystemClassLoader() for details)
java.library.path List of paths to search when loading libraries
java.io.tmpdir Default temp file path
java.compiler Name of JIT compiler to use
os.name Operating system name
os.arch Operating system architecture
os.version Operating system version
file.separator File separator («/» on UNIX)
path.separator Path separator («:» on UNIX)
line.separator Line separator («\n» on UNIX)
user.name User’s account name
user.home User’s home directory
user.dir User’s current working directory

Multiple paths in a system property value are separated by the path separator character of the platform.

Note that even if the security manager does not permit the getProperties operation, it may choose to permit the getProperty(String) operation.

lineSeparator

On UNIX systems, it returns «\n» ; on Microsoft Windows systems it returns «\r\n» .

setProperties

The argument becomes the current set of system properties for use by the getProperty(String) method. If the argument is null , then the current set of system properties is forgotten.

getProperty

If there is no current set of system properties, a set of system properties is first created and initialized in the same manner as for the getProperties method.

getProperty

If there is no current set of system properties, a set of system properties is first created and initialized in the same manner as for the getProperties method.

setProperty

clearProperty

getenv

If a security manager exists, its checkPermission method is called with a RuntimePermission(«getenv.»+name) permission. This may result in a SecurityException being thrown. If no exception is thrown the value of the variable name is returned.

System properties and environment variables are both conceptually mappings between names and values. Both mechanisms can be used to pass user-defined information to a Java process. Environment variables have a more global effect, because they are visible to all descendants of the process which defines them, not just the immediate Java subprocess. They can have subtly different semantics, such as case insensitivity, on different operating systems. For these reasons, environment variables are more likely to have unintended side effects. It is best to use system properties where possible. Environment variables should be used when a global effect is desired, or when an external system interface requires an environment variable (such as PATH ).

On UNIX systems the alphabetic case of name is typically significant, while on Microsoft Windows systems it is typically not. For example, the expression System.getenv(«FOO»).equals(System.getenv(«foo»)) is likely to be true on Microsoft Windows.

getenv

If the system does not support environment variables, an empty map is returned.

The returned map will never contain null keys or values. Attempting to query the presence of a null key or value will throw a NullPointerException . Attempting to query the presence of a key or value which is not of type String will throw a ClassCastException .

The returned map and its collection views may not obey the general contract of the Object.equals(java.lang.Object) and Object.hashCode() methods.

The returned map is typically case-sensitive on all platforms.

If a security manager exists, its checkPermission method is called with a RuntimePermission(«getenv.*») permission. This may result in a SecurityException being thrown.

When passing information to a Java subprocess, system properties are generally preferred over environment variables.

System currenttimemillis java что возвращает

Before java 8 the compiler used to take it from the java.util package. But later since the use of date and time became important in every software and android application, java developed the date class after java 8. Date and time class via java.util package has been duplicated now. Java uses date and time class after the release of version java 8 to store the date and time. Now java usually stores Date in a typical fashion such that the number of milliseconds passed since 1 Jan 1970 in a long data type. Since it stores milliseconds the accuracy of the exact time increases.

The package view of the method is as follows:

Syntax: Getting milliseconds

Note: This return the number of milliseconds passed since 1970 as 00:00 1 January 1970 is considered as epoch time. Similarly, we can find out years, months, hours and rest of data from milliseconds.

(System.currentTimeMillis()) / 1000) Returns Seconds passed

(System.currentTimeMillis()) / 1000 / 60) Returns Minutes passed

(System.currentTimeMillis()) / 1000 / 60 / 60); Returns Hours passed

(System.currentTimeMillis()) / 1000 / 60 / 60 / 24); Returns days passed

(System.currentTimeMillis()) / 1000 / 60 / 60 / 24 / 365); Returns Years passed

Example 1: Here all outputs are obtained from the epoch time set which is 1 January 1970. We can easily find seconds now if we divide the millisecond by 1000 we will get the number of seconds passed since 1 Jan 1970.

Class System

For simple stand-alone Java applications, a typical way to write a line of output data is:

See the println methods in class PrintStream .

Typically this stream corresponds to display output or another output destination specified by the host environment or user. By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out , has been redirected to a file or other destination that is typically not continuously monitored. The encoding used in the conversion from characters to bytes is equivalent to Console.charset() if the Console exists, Charset.defaultCharset() otherwise.

Method Details

setIn

setOut

setErr

console

inheritedChannel

In addition to the network-oriented channels described in inheritedChannel , this method may return other kinds of channels in the future.

setSecurityManager

Otherwise, the argument is established as the current security manager. If the argument is null and no security manager has been established, then no action is taken and the method simply returns.

getSecurityManager

currentTimeMillis

See the description of the class Date for a discussion of slight discrepancies that may arise between «computer time» and coordinated universal time (UTC).

nanoTime

This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) — no guarantees are made except that the resolution is at least as good as that of currentTimeMillis() .

Differences in successive calls that span greater than approximately 292 years (2 63 nanoseconds) will not correctly compute elapsed time due to numerical overflow.

The values returned by this method become meaningful only when the difference between two such values, obtained within the same instance of a Java virtual machine, is computed.

For example, to measure how long some code takes to execute:

To compare elapsed time against a timeout, use instead of because of the possibility of numerical overflow.

arraycopy

If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array.

If dest is null , then a NullPointerException is thrown.

If src is null , then a NullPointerException is thrown and the destination array is not modified.

  • The src argument refers to an object that is not an array.
  • The dest argument refers to an object that is not an array.
  • The src argument and dest argument refer to arrays whose component types are different primitive types.
  • The src argument refers to an array with a primitive component type and the dest argument refers to an array with a reference component type.
  • The src argument refers to an array with a reference component type and the dest argument refers to an array with a primitive component type.
  • The srcPos argument is negative.
  • The destPos argument is negative.
  • The length argument is negative.
  • srcPos+length is greater than src.length , the length of the source array.
  • destPos+length is greater than dest.length , the length of the destination array.

Otherwise, if any actual component of the source array from position srcPos through srcPos+length-1 cannot be converted to the component type of the destination array by assignment conversion, an ArrayStoreException is thrown. In this case, let k be the smallest nonnegative integer less than length such that src[srcPos+ k ] cannot be converted to the component type of the destination array; when the exception is thrown, source array components from positions srcPos through srcPos+ k -1 will already have been copied to destination array positions destPos through destPos+ k -1 and no other positions of the destination array will have been modified. (Because of the restrictions already itemized, this paragraph effectively applies only to the situation where both arrays have component types that are reference types.)

identityHashCode

getProperties

The current set of system properties for use by the getProperty(String) method is returned as a Properties object. If there is no current set of system properties, a set of system properties is first created and initialized. This set of system properties includes a value for each of the following keys unless the description of the associated value indicates that the value is optional.

Shows property keys and associated values

Key Description of Associated Value
java.version Java Runtime Environment version, which may be interpreted as a Runtime.Version
java.version.date Java Runtime Environment version date, in ISO-8601 YYYY-MM-DD format, which may be interpreted as a LocalDate
java.vendor Java Runtime Environment vendor
java.vendor.url Java vendor URL
java.vendor.version Java vendor version (optional)
java.home Java installation directory
java.vm.specification.version Java Virtual Machine specification version, whose value is the feature element of the runtime version
java.vm.specification.vendor Java Virtual Machine specification vendor
java.vm.specification.name Java Virtual Machine specification name
java.vm.version Java Virtual Machine implementation version which may be interpreted as a Runtime.Version
java.vm.vendor Java Virtual Machine implementation vendor
java.vm.name Java Virtual Machine implementation name
java.specification.version Java Runtime Environment specification version, whose value is the feature element of the runtime version
java.specification.vendor Java Runtime Environment specification vendor
java.specification.name Java Runtime Environment specification name
java.class.version Java class format version number
java.class.path Java class path (refer to ClassLoader.getSystemClassLoader() for details)
java.library.path List of paths to search when loading libraries
java.io.tmpdir Default temp file path
java.compiler Name of JIT compiler to use
os.name Operating system name
os.arch Operating system architecture
os.version Operating system version
file.separator File separator («/» on UNIX)
path.separator Path separator («:» on UNIX)
line.separator Line separator («\n» on UNIX)
user.name User’s account name
user.home User’s home directory
user.dir User’s current working directory
native.encoding Character encoding name derived from the host environment and/or the user’s settings. Setting this system property has no effect.

Multiple paths in a system property value are separated by the path separator character of the platform.

Note that even if the security manager does not permit the getProperties operation, it may choose to permit the getProperty(String) operation.

lineSeparator

On UNIX systems, it returns «\n» ; on Microsoft Windows systems it returns «\r\n» .

setProperties

The argument becomes the current set of system properties for use by the getProperty(String) method. If the argument is null , then the current set of system properties is forgotten.

getProperty

If there is no current set of system properties, a set of system properties is first created and initialized in the same manner as for the getProperties method.

getProperty

If there is no current set of system properties, a set of system properties is first created and initialized in the same manner as for the getProperties method.

setProperty

clearProperty

getenv

If a security manager exists, its checkPermission method is called with a RuntimePermission(«getenv.»+name) permission. This may result in a SecurityException being thrown. If no exception is thrown the value of the variable name is returned.

System properties and environment variables are both conceptually mappings between names and values. Both mechanisms can be used to pass user-defined information to a Java process. Environment variables have a more global effect, because they are visible to all descendants of the process which defines them, not just the immediate Java subprocess. They can have subtly different semantics, such as case insensitivity, on different operating systems. For these reasons, environment variables are more likely to have unintended side effects. It is best to use system properties where possible. Environment variables should be used when a global effect is desired, or when an external system interface requires an environment variable (such as PATH ).

On UNIX systems the alphabetic case of name is typically significant, while on Microsoft Windows systems it is typically not. For example, the expression System.getenv(«FOO»).equals(System.getenv(«foo»)) is likely to be true on Microsoft Windows.

getenv

If the system does not support environment variables, an empty map is returned.

The returned map will never contain null keys or values. Attempting to query the presence of a null key or value will throw a NullPointerException . Attempting to query the presence of a key or value which is not of type String will throw a ClassCastException .

The returned map and its collection views may not obey the general contract of the Object.equals(java.lang.Object) and Object.hashCode() methods.

The returned map is typically case-sensitive on all platforms.

If a security manager exists, its checkPermission method is called with a RuntimePermission(«getenv.*») permission. This may result in a SecurityException being thrown.

When passing information to a Java subprocess, system properties are generally preferred over environment variables.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *