You can generate a timestamp in JavaScript by using the Date
object and its .getTime()
method. The .getTime()
method returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.
Example:
let timestamp = new Date().getTime();
console.log(timestamp);
You can also generate a timestamp in a more human-readable format using the toString()
method.
let timestamp = new Date().toString();
console.log(timestamp);
You can also create a string with a specific format using the toLocaleString()
method.
let timestamp = new Date().toLocaleString();
console.log(timestamp);
This will return a string in the format of: “Month Day, Year Hour:Minutes:Seconds”
You can also pass the options to format the date and time as per the requirement.
let timestamp = new Date().toLocaleString('en-US', {
month: 'short',
day: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
console.log(timestamp);
This will return the timestamp in format : ‘MM/DD/YY HH:mm:ss’
You can also use libraries like moment.js
which provides a more powerful way to handle dates and timestamps.
Also Read:
- Difference Between encodeURIComponent() And encodeURI()
- Convert Comma Separated String Into An Array In JavaScript
- How To Check If A String Is Empty In JavaScript
- How To Sort An Array Of Numbers In JavaScript
- How To Return Multiple Values From A Function In JavaScript
- How To Get The Current URL With JavaScript
- How To Include A JavaScript File In Another JavaScript File
- How To Detect Screen Resolution With JavaScript
- How To parse JSON Into JavaScript
- How To Add Elements To An Array In JavaScript
- How To Generate A Timestamp In JavaScript
- How To Convert A JavaScript Object To JSON String
- How To Add An Element To The Beginning Of An Array
- How To Get The Value From The Input Field In JavaScript
- Adjust The iFrame Height To Fit With Content In JavaScript
- Call Two Functions From The Same onClick Event In JavaScript
- How To Detect When A Window Is Resized Using JavaScript
- How To Reset A Form With JavaScript
- How To Pass JavaScript Variables To PHP
- Difference Between PHP And JavaScript
- Armstrong Number In JavaScript
- How To Determine If A Number Is Odd Or Even In JavaScript
- How To Check If A Number Is A Palindrome In JavaScript
- How To Convert Strings To Uppercase In JavaScript
- How To Convert A String To Lowercase In JavaScript
- Code To Check If Age Is Not Less Than 18 Years In JavaScript
- How To Reverse A Number In JavaScript
- How To Check If A Number Is Prime Using JavaScript
- How To Find Factorial Of A Number In JavaScript
- Sum Of Two Numbers In JavaScript
- How To Display The Current Date And Time In JavaScript