How convert dd mm yyyy string to date in javascript?

How to convert a date in format 23/10/2015 into a JavaScript Date format:

Fri Oct 23 2015 15:24:53 GMT+0530 (India Standard Time)

This question is tagged with javascript date

~ Asked on 2015-10-23 10:01:38

The Best Answer is


MM/DD/YYYY format

If you have the MM/DD/YYYY format which is default for JavaScript, you can simply pass your string to Date(string) constructor. It will parse it for you.

_x000D_

_x000D_

var dateString = "10/23/2015"; // Oct 23_x000D_
_x000D_
var dateObject = new Date(dateString);_x000D_
_x000D_
document.body.innerHTML = dateObject.toString();

_x000D_

_x000D_

_x000D_

DD/MM/YYYY format - manually

If you work with this format, then you can split the date in order to get day, month and year separately and then use it in another constructor - Date(year, month, day):

_x000D_

_x000D_

var dateString = "23/10/2015"; // Oct 23_x000D_
_x000D_
var dateParts = dateString.split("/");_x000D_
_x000D_
// month is 0-based, that's why we need dataParts[1] - 1_x000D_
var dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]); _x000D_
_x000D_
document.body.innerHTML = dateObject.toString();

_x000D_

_x000D_

_x000D_

For more information, you can read article about Date at Mozilla Developer Network.

DD/MM/YYYY - using moment.js library

Alternatively, you can use moment.js library, which is probably the most popular library to parse and operate with date and time in JavaScript:

_x000D_

_x000D_

var dateString = "23/10/2015"; // Oct 23_x000D_
_x000D_
var dateMomentObject = moment(dateString, "DD/MM/YYYY"); // 1st argument - string, 2nd argument - format_x000D_
var dateObject = dateMomentObject.toDate(); // convert moment.js object to Date object_x000D_
_x000D_
document.body.innerHTML = dateObject.toString();

_x000D_

<script src="https://momentjs.com/downloads/moment.min.js"></script>

_x000D_

_x000D_

_x000D_

In all three examples dateObject variable contains an object of type Date, which represents a moment in time and can be further converted to any string format.

~ Answered on 2015-10-23 10:05:41


I found the default JS date formatting didn't work.

So I used toLocaleString with options

const event = new Date();
const options = { dateStyle: 'short' };
const date = event.toLocaleString('en', options);

to get: DD/MM/YYYY format

See docs for more formatting options: https://www.w3schools.com/jsref/jsref_tolocalestring.asp

~ Answered on 2021-02-04 11:38:28


Most Viewed Questions:

  • how to call a method in another Activity from Activity
  • Making an API call in Python with an API that requires a bearer token
  • How to disable Google asking permission to regularly check installed apps on my phone?
  • How to make button fill table cell
  • ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import
  • What's the difference between Docker Compose vs. Dockerfile
  • how to sync windows time from a ntp time server in command
  • How to get Spinner selected item value to string?
  • How to convert Map keys to array?
  • How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?
  • Property 'value' does not exist on type EventTarget in TypeScript
  • How to add hamburger menu in bootstrap
  • Change text from "Submit" on input tag
  • Disable Button in Angular 2
  • How to check if array element exists or not in javascript?
  • 403 Forbidden error when making an ajax Post request in Django framework
  • Where is the Android SDK folder located?
  • Android SDK location
  • Java swing application, close one window and open another when button is clicked
  • Why can I not create a wheel in python?
  • Check if decimal value is null
  • How do you run `apt-get` in a dockerfile behind a proxy?
  • Append an int to a std::string
  • Right Align button in horizontal LinearLayout
  • How do I install the yaml package for Python?
  • return string with first match Regex
  • Font.createFont(..) set color and size (java.awt.Font)
  • How to solve npm install throwing fsevents warning on non-MAC OS?
  • Java 8, Streams to find the duplicate elements
  • How to iterate over rows in a DataFrame in Pandas
  • Convert floats to ints in Pandas?
  • JSON.net: how to deserialize without using the default constructor?
  • What is the keyguard in Android?
  • SCCM 2012 application install "Failed" in client Software Center
  • Invert colors of an image in CSS or JavaScript
  • What is the `zero` value for time.Time in Go?
  • nodejs vs node on ubuntu 12.04
  • Angularjs $http.get().then and binding to a list
  • AngularJS: Service vs provider vs factory
  • JavaScript, get date of the next day
  • Exception: "URI formats are not supported"
  • Making an image act like a button
  • How to convert a Scikit-learn dataset to a Pandas dataset?
  • linking jquery in html
  • How to get current timestamp in milliseconds since 1970 just the way Java gets
  • How to cherry-pick from a remote branch?
  • Where does linux store my syslog?
  • xampp MySQL does not start
  • how to read xml file from url using php
  • Replace non-ASCII characters with a single space
  • How to join a slice of strings into a single string?
  • How to make an android app to always run in background?
  • Spring Boot Java Config Set Session Timeout
  • Webpack how to build production code and how to use it
  • Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape
  • How to get all registered routes in Express?
  • What is the difference between VFAT and FAT32 file systems?
  • Jquery UI tooltip does not support html content
  • How to use not contains() in xpath?
  • You have to be inside an angular-cli project in order to use the build command after reinstall of angular-cli
  • Git: How to remove remote origin from Git repo
  • Access to Image from origin 'null' has been blocked by CORS policy
  • jQuery get an element by its data-id
  • Is there a quick change tabs function in Visual Studio Code?
  • The #include<iostream> exists, but I get an error: identifier "cout" is undefined. Why?
  • How to Set AllowOverride all
  • How to define unidirectional OneToMany relationship in JPA
  • Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?
  • How can I read the contents of an URL with Python?
  • JetBrains / IntelliJ keyboard shortcut to collapse all methods
  • InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately
  • window.open(url, '_blank'); not working on iMac/Safari
  • Simple If/Else Razor Syntax
  • How to Position a table HTML?
  • shell-script headers (#!/bin/sh vs #!/bin/csh)
  • Playing a MP3 file in a WinForm application
  • Check div is hidden using jquery
  • Difference between setTimeout with and without quotes and parentheses
  • cout is not a member of std
  • How to remove all the occurrences of a char in c++ string
  • Font Awesome not working, icons showing as squares
  • Display all items in array using jquery
  • How to set maximum height for table-cell?
  • cursor.fetchall() vs list(cursor) in Python
  • Launch an event when checking a checkbox in Angular2
  • C program to check little vs. big endian
  • Converting string to number in javascript/jQuery
  • How do I request and receive user input in a .bat and use it to run a certain program?
  • Could not connect to Redis at 127.0.0.1:6379: Connection refused with homebrew
  • open the file upload dialogue box onclick the image
  • Bi-directional Map in Java?
  • .bashrc: Permission denied
  • How to create JSON object Node.js
  • Delete files or folder recursively on Windows CMD
  • Wordpress keeps redirecting to install-php after migration
  • Simple mediaplayer play mp3 from file path?
  • Simulate user input in bash script
  • How to enable multidexing with the new Android Multidex support library
  • missing FROM-clause entry for table
  • fatal: bad default revision 'HEAD'
  • How to clear all input fields in a specific div with jQuery?
  • How are people unit testing with Entity Framework 6, should you bother?
  • VBA (Excel) Initialize Entire Array without Looping
  • How to receive serial data using android bluetooth
  • Writing a dictionary to a csv file with one line for every 'key: value'
  • Remove Blank option from Select Option with AngularJS
  • how to get all child list from Firebase android
  • Bootstrap 3 truncate long text inside rows of a table in a responsive way
  • What is the difference between json.dump() and json.dumps() in python?
  • When to use @QueryParam vs @PathParam
  • React Native version mismatch
  • Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'
  • lexical or preprocessor issue file not found occurs while archiving?
  • How to fix UITableView separator on iOS 7?
  • TypeError: $.ajax(...) is not a function?
  • Spring Boot: How can I set the logging level with application.properties?
  • javascript: Disable Text Select
  • How to check whether a given string is valid JSON in Java
  • how to create virtual host on XAMPP
  • How do I parse a URL query parameters, in Javascript?
  • Count lines in large files
  • Disable button in angular with two conditions?
  • Oracle insert from select into table with more columns
  • Angular 2 change event on every keypress
  • Remove blue border from css custom-styled button in Chrome
  • Read XML file into XmlDocument
  • Joining Spark dataframes on the key
  • Retrieving a Foreign Key value with django-rest-framework serializers
  • How to make sure that a certain Port is not occupied by any other process
  • Unable to install Android Studio in Ubuntu
  • How to right-align form input boxes?
  • Gradle failed to resolve library in Android Studio
  • WebSocket with SSL
  • Typescript: How to extend two classes?
  • Job for mysqld.service failed See "systemctl status mysqld.service"
  • The filename, directory name, or volume label syntax is incorrect inside batch
  • MongoDB via Mongoose JS - What is findByID?
  • how to send an array in url request
  • Remove elements from collection while iterating
  • Passing the argument to CMAKE via command prompt
  • Numpy AttributeError: 'float' object has no attribute 'exp'
  • Django: save() vs update() to update the database?
  • Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'
  • MySQL Trigger: Delete From Table AFTER DELETE
  • VBA code to show Message Box popup if the formula in the target cell exceeds a certain value
  • How do I reset a jquery-chosen select option with jQuery?
  • Padding is invalid and cannot be removed?
  • MVC3 EditorFor readOnly
  • Sniffing/logging your own Android Bluetooth traffic
  • Using sendmail from bash script for multiple recipients

How do you convert a string to a date in JavaScript?

Use the Date() constructor to convert a string to a Date object, e.g. const date = new Date('2022-09-24') . The Date() constructor takes a valid date string as a parameter and returns a Date object. Copied! We used the Date() constructor to convert a string to a Date object.

How do I convert a string to a date?

Java String to Date Example.
import java.text.SimpleDateFormat;.
import java.util.Date;.
public class StringToDateExample1 {.
public static void main(String[] args)throws Exception {.
String sDate1="31/12/1998";.
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1);.
System.out.println(sDate1+"\t"+date1);.

What date format is DD MMM YYYY JavaScript?

There is no native format in JavaScript for” dd-mmm-yyyy”. To get the date format “dd-mmm-yyyy”, we are going to use regular expression in JavaScript. The regular expression in JavaScript is used to find the pattern in a string. So we are going to find the “dd-mmm-yyyy” pattern in the string using match() method.

How do you format a date mm dd yyyy?

First, pick the cells that contain dates, then right-click and select Format Cells. Select Custom in the Number Tab, then type 'dd-mmm-yyyy' in the Type text box, then click okay. It will format the dates you specify.