zaro

How to get current timestamp as string in JavaScript?

Published in JavaScript Date Time 4 mins read

To get the current date and time as a string in JavaScript, you typically create a Date object and then use one of its many methods to format it into a string representation. The choice of method depends on the desired format, such as an international standard, a locale-specific format, or a simple representation of the numeric timestamp.

Getting a Human-Readable Date/Time String

The Date object in JavaScript provides various methods to convert the current date and time into different string formats.

Standard UTC String (ISO 8601 Format)

For a standardized, machine-readable string in ISO 8601 format (e.g., "YYYY-MM-DDTHH:mm:ss.sssZ"), use the toISOString() method. This format is excellent for data interchange and logging as it represents UTC (Coordinated Universal Time).

const currentDate = new Date();
const isoString = currentDate.toISOString();
console.log(isoString); // Example: "2023-10-27T10:30:00.000Z"

Localized Date/Time String

If you need a string formatted according to the user's locale (their geographic region and language settings), toLocaleString() is ideal. You can customize options for the date, time, and even the locale itself.

const currentDate = new Date();
const localizedString = currentDate.toLocaleString();
console.log(localizedString); // Example: "10/27/2023, 10:30:00 AM" (depends on locale)

// Customizing locale and options
const customLocalized = currentDate.toLocaleString('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
});
console.log(customLocalized); // Example: "Friday, October 27, 2023 at 10:30:00"

Other Common String Formats

JavaScript's Date object offers several other methods for different string representations:

  • toUTCString(): Returns a string representation of the date in UTC.
    const currentDate = new Date();
    const utcString = currentDate.toUTCString();
    console.log(utcString); // Example: "Fri, 27 Oct 2023 10:30:00 GMT"
  • toString(): Returns a human-readable string representation of the date and time in the local timezone.
    const currentDate = new Date();
    const defaultString = currentDate.toString();
    console.log(defaultString); // Example: "Fri Oct 27 2023 10:30:00 GMT+0000 (Coordinated Universal Time)"
  • toDateString(): Returns only the date portion of the string.
    const currentDate = new Date();
    const dateOnly = currentDate.toDateString();
    console.log(dateOnly); // Example: "Fri Oct 27 2023"
  • toTimeString(): Returns only the time portion of the string.
    const currentDate = new Date();
    const timeOnly = currentDate.toTimeString();
    console.log(timeOnly); // Example: "10:30:00 GMT+0000 (Coordinated Universal Time)"

Getting the Numeric Timestamp as a String

In JavaScript, a "timestamp" typically refers to the number of milliseconds that have elapsed since January 1, 1970, 00:00:00 UTC (the Unix Epoch). While this value is numeric, you can easily convert it to a string if needed.

Using getTime()

To obtain this numeric timestamp, create a new Date object and then use its getTime() method. This method returns the timestamp as a number. To convert it to a string, you can simply append an empty string or use toString().

const currentDate = new Date();
const numericTimestamp = currentDate.getTime(); // Returns a number, e.g., 1678886400000
console.log(typeof numericTimestamp); // Output: "number"

// Convert numeric timestamp to string
const timestampAsString = String(numericTimestamp); // Or: numericTimestamp.toString();
console.log(timestampAsString); // Example: "1678886400000"
console.log(typeof timestampAsString); // Output: "string"

Summary of Timestamp String Formats

Here's a quick comparison of common methods for getting current timestamp strings:

Method Description Example Output (approx.) Use Case
new Date().toISOString() Standardized UTC date and time (ISO 8601). 2023-10-27T10:30:00.000Z Data interchange, logging, API requests.
new Date().toLocaleString() Localized date and time based on user settings. 10/27/2023, 10:30:00 AM Displaying to end-users.
new Date().toUTCString() Standard UTC date and time. Fri, 27 Oct 2023 10:30:00 GMT Displaying UTC time without milliseconds.
String(new Date().getTime()) Numeric Unix timestamp (milliseconds since epoch) as string. 1678886400000 Unique identifiers, internal system timing.
new Date().toString() Default local date and time string. Fri Oct 27 2023 10:30:00 GMT+0000 (...) Quick debugging or informal display.

Best Practices

  • For storing or transferring dates: Use toISOString() as it provides a consistent, universally understood format.
  • For displaying to users: Use toLocaleString() to ensure the date and time are presented in a format familiar to their region.
  • For unique IDs or precise timing: Use getTime() for the numeric timestamp. Convert it to a string only if the target system requires a string.

For more detailed information on JavaScript's Date object and its methods, refer to the MDN Web Docs for the Date object, toISOString(), toLocaleString(), and getTime().