Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format a DateTime string in javascript from using slashes to using hypens?

Tags:

javascript

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?

like image 891
williamsandonz Avatar asked Jan 22 '14 18:01

williamsandonz


People also ask

How do you read dates with slashes?

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.

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

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.

Can JavaScript handle dates and time?

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.


2 Answers

Use string.replace

date = date.replace(/\//g, '-');

FIDDLE

If for some reason you don't want to use a regex

date = date.split('/').join('-');
like image 158
adeneo Avatar answered Nov 14 '22 23:11

adeneo


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.

like image 32
DutGRIFF Avatar answered Nov 15 '22 00:11

DutGRIFF