Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript
  • Vue.js
  • D3.js
  • Collect.js
  • Underscore.js
  • Moment.js
  • Ember.js
  • Tensorflow.js
  • Fabric.js
  • JS Formatter
  • JavaScript
  • Web Technology
Open In App
Next Article:
How to format current date in MM/DD/YYYY HH:MM:SS format using JavaScript ?
Next article icon

How to Format Datetime to YYYY-MM-DD HH:MM:SS in Moment.js?

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Moment.js, formatting the date in the proper format is important for consistent data presentation and manipulation. The library provides various methods to handle and transform dates. You can use direct formatting with format(), manipulate ISO strings, or work with Unix timestamps to achieve the desired 'YYYY-MM-DD HH:mm:ss' format.

Table of Content

  • Using format Method Directly
  • Using toISOString and String Manipulation
  • Using unix Timestamp with Manual Formatting

Run the below command before running the code in your local system:

npm i moment

1. Using format Method Directly

In this approach, we are using the format method directly to convert the input date string from 'MM/DD/YYYY HH:mm:ss' format to 'YYYY-MM-DD HH:mm:ss'. By parsing the input date with the specified format and then formatting it using format(), we achieve the desired output format.

Example: The below example uses the format Method Directly to Format datetime to YYYY-MM-DD HH:mm:ss in moment.js.

JavaScript
// script.js  const moment = require('moment'); const date = moment('07/24/2024 08:00:00', 'MM/DD/YYYY HH:mm:ss'); const res = date.format('YYYY-MM-DD HH:mm:ss'); console.log(`Formatted date: ${res}`); 

Note: Use command, node script.js to see console.

Output

Formatted date: 2024-07-24 08:00:00

2. Using toISOString and String Manipulation

In this approach, we are using toISOString to convert the Moment.js object to a standardized ISO string. We then extract the relevant portion of the ISO string (up to the first 19 characters) and replace the 'T' separator with a space to format it as 'YYYY-MM-DD HH:mm:ss'.

Example: The below example uses the format Method Directly to Format datetime to YYYY-MM-DD HH:mm:ss in moment.js.

JavaScript
// script.js  const moment = require('moment'); const date = moment('2024-07-24T08:00:00Z', 'YYYY-MM-DDTHH:mm:ssZ'); const isoString = date.toISOString(); const res = isoString.substring(0, 19).replace('T', ' '); console.log(`Formatted date: ${res}`); 

Note: Use command, node script.js to see console.

Output

Formatted date: 2024-07-24 08:00:00

3. Using unix Timestamp with Manual Formatting

In this approach, we are using a Unix timestamp to handle date formatting. We first convert the input date string into a Unix timestamp, then use moment.unix() to create a new Moment.js object from this timestamp. Finally, we format this object to 'YYYY-MM-DD HH:mm:ss', resulting in the desired date format.

Example: The below example uses the format Method Directly to Format datetime to YYYY-MM-DD HH:mm:ss in moment.js.

JavaScript
// script.js  const moment = require('moment'); const date = moment('Wed Jul 24 2024 08:00:00', 'ddd MMM DD YYYY HH:mm:ss'); const unixTimestamp = date.unix(); const res = moment.unix(unixTimestamp).format('YYYY-MM-DD HH:mm:ss');  console.log(`Formatted date: ${res}`); 

Note: Use command, node script.js to see console.

Output:

Formatted date: 2024-07-24 08:00:00

Next Article
How to format current date in MM/DD/YYYY HH:MM:SS format using JavaScript ?

G

gauravggeeksforgeeks
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Moment.js

Similar Reads

  • Convert datetime string to YYYY-MM-DD-HH:MM:SS format in Python
    In this article, we are going to convert the DateTime string into the %Y-%m-%d-%H:%M:%S format. For this task strptime() and strftime() function is used. strptime() is used to convert the DateTime string to DateTime in the format of year-month-day hours minutes and seconds Syntax: datetime.strptime(
    2 min read
  • How to format the current date in MM/DD/YYYY HH:MM:SS format using Node?
    The current date can be formatted by using Nodejs modules like Date Object or libraries like moment.js. Table of Content Using Node.js Date ObjectUsing Moment.js LibraryMethod 1: Using Node.js Date Object:The JavaScript Date Object can be used in the program by using the following command. const dat
    3 min read
  • How to format current date in MM/DD/YYYY HH:MM:SS format using JavaScript ?
    Given a date and the task is to format the current date in MM/DD/YYYY HH:MM:SS format. Here are a few of the most techniques discussed with the help of JavaScript. Approach 1: Store the current date in variable.Use the string concatenation technique to insert / and : in between the month-day and day
    2 min read
  • How to Format Date with Moment.js?
    Formatting dates is essential for presenting date and time information in a way that's readable and useful for users. Moment.js provides several methods for formatting dates from simple and predefined formats to more complex and localized representations. Below are different approaches: Table of Con
    2 min read
  • How to Set input type date in dd-mm-yyyy format using HTML?
    In HTML, you can use the <input> element with the type date to allow users to pick a date. However, the format used for displaying the date may vary depending on the browser and the user's locale settings. By default, the browser uses the ISO format (yyyy-mm-dd), which is not the same as dd-mm
    2 min read
  • How to use moment.js to change date format in jQuery ?
    Using Moment.js to change date format in jQuery involves importing the Moment.js library and utilizing its functions to parse, manipulate, and format dates. You can easily convert dates into various formats by calling moment(date).format(desiredFormat) to display the date in your preferred format. m
    2 min read
  • How to Use format() on a Moment.js Duration?
    The format() function can be used to convert moment objects into human-readable strings, but it does not directly format moment.duration objects. To format durations effectively, you need to work with moment objects by adding durations to a base date and then formatting the resulting date-time. Run
    3 min read
  • How To Format JavaScript Date as yyyy-mm-dd?
    We use JavaScript built-in help methods from the Date class that help us to create a formatted version of the current date in the form of yyyy-mm-dd. These are the approaches used to format JavaScript date as yyyy-mm-dd. Table of Content Using the ISO String Method USing JavaScript Method1. Using th
    2 min read
  • How to extract date from a string in dd-mmm-yyyy format in JavaScript ?
    In this article, we will see how to extract date from a given string of format "dd-mmm-yyyy" in JavaScript. We have a string, and we want to extract the date format "dd-mmm-yyyy" from the string. Example: // Stringstr = "India got freedom on 15-Aug-1947"// Extracted date from given string in // "dd-
    2 min read
  • How to Format Date and Subtract Days Using Moment.js?
    Moment.js is useful in performing date computation and formatting in JavaScript applications. It provides a simple and intuitive API for parsing, validating, manipulating, and formatting dates. we are going to subtract days and format that. These are the following approaches to formatting dates and
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences