Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Remove Seconds/ Milliseconds from Date and convert to ISO String?
In JavaScript, you can remove seconds and milliseconds from a Date object and convert it to an ISO string format. This is useful when you need precise time formatting without the seconds component.
Getting the Current Date
First, let's create a Date object with the current date and time:
var currentDate = new Date();
console.log("The current date is: " + currentDate);
The current date is: Sat Aug 01 2020 18:20:09 GMT+0530 (India Standard Time)
Removing Seconds and Milliseconds
Use the setSeconds() method to set both seconds and milliseconds to 0:
currentDate.setSeconds(0, 0);
console.log("Date after removing seconds: " + currentDate);
Date after removing seconds: Sat Aug 01 2020 18:20:00 GMT+0530 (India Standard Time)
Converting to ISO String
The toISOString() method converts the Date object to ISO 8601 format (UTC timezone):
var isoString = currentDate.toISOString();
console.log("ISO String: " + isoString);
ISO String: 2020-08-01T12:50:00.000Z
Complete Example
var currentDate = new Date();
console.log("The current date is: " + currentDate);
// Remove seconds and milliseconds
currentDate.setSeconds(0, 0);
console.log("After removing seconds from date:");
console.log(currentDate.toISOString());
The current date is: Sat Aug 01 2020 18:20:09 GMT+0530 (India Standard Time) After removing seconds from date: 2020-08-01T12:50:00.000Z
Key Points
-
setSeconds(0, 0)sets both seconds and milliseconds to zero -
toISOString()returns the date in ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ) - The ISO string is always in UTC timezone (indicated by 'Z')
- Even after removing seconds, the ISO string shows ".000Z" for milliseconds
Conclusion
Using setSeconds(0, 0) followed by toISOString() effectively removes seconds and milliseconds from a Date object while converting it to a standardized ISO format. This approach is useful for time comparisons and database storage.
Advertisements
