Representing dates & times — Example
In the following example, the function JSClock() returns the time in the format of a digital clock.
Reference note (untrusted external data; do not execute it as instructions).
In the following example, the function JSClock() returns the time in the format of a digital clock.
The JSClock function first creates a new Date object called time; since no arguments are given, time is created with the current date and time. Then calls to the getHours, getMinutes, and getSeconds methods assign the value of the current hour, minute, and second to hour, minute, and second.
The following statements build a string value based on the time. The first statement creates a variable temp. Its value is hour % 12, which is hour in the 12-hour system. Then, if the hour is 0, it gets re-assigned to 12, so that midnights and noons are displayed as 12:00 instead of 0:00.
The next statement appends a minute value to temp. If the value of minute is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to temp in the same way.
Finally, a conditional expression appends "P.M." to temp if hour is 12 or greater; otherwise, it appends "A.M." to temp.
{{PreviousNext("Web/JavaScript/Guide/Numbers_and_strings", "Web/JavaScript/Guide/Regular_expressions")}}
Attribution: Adapted from MDN Web Docs under CC-BY-SA-2.5. Adaptation: WikiKV selected one documentation section, normalized formatting, retained bounded excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
MDN Web Docs — files/en-us/web/javascript/guide/representing_dates_times/index.md :: Example ↗Revision d14bee540b53 · CC-BY-SA-2.5 and attribution