I have an input date string in the following format:
yyyy/mm/dd
This is my desired output date string format:
yyyy-mm-dd
Is there a built-in way to do this in Javascript?
It is therefore preferable to write the name of the month. When writing the date by numbers only, one can separate them by using a hyphen (-), a slash (/), or a dot (.): 05-07-2013, or 05/07/2013, or 05.07. 2013. Omitting the initial zero in the numbers smaller than 10 is also accepted: 5-7-2013, 5/7/2013, or 5.7.
Just concatenate your date string (using ISO format) with "T00:00:00" in the end and use the JavaScript Date() constructor, like the example below. const dateString = '2014-04-03' var mydate = new Date(dateString + "T00:00:00"); console.
The Date object is a built-in object in JavaScript that stores the date and time. It provides a number of built-in methods for formatting and managing that data. By default, a new Date instance without arguments provided creates an object corresponding to the current date and time.
Use string.replace
date = date.replace(/\//g, '-');
FIDDLE
If for some reason you don't want to use a regex
date = date.split('/').join('-');
Adeneo's answer did solve this particular case but I would like to show how you can get this to any format you want. We start by getting the date that is shown as a date object by the calls new Date()
ad passing it the date string:
var dateStr = "1991/01/11";
var d = new Date(dateStr);
Now we can call any of the getters listed here to get that value and build out the desired string:
var curr_date = d.getDate();
var curr_month = d.getMonth();
curr_month++; //We add +1 because Jan is indexed at 0 instead of 1
var curr_year = d.getFullYear();
console.log(curr_year + "-" + curr_month + "-" + curr_date);
This allows us to build any format we want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With