Convert Date from one format to another format in JavaScript
Asked Answered
C

5

15

I have a string of a date in javascript in format #1. I need to convert it to format #2.

The problem starts when one format is "dd/mm/yy" and the other is "mm/dd/yy".

The formats change dynamically and I have the formats as strings, but I need a function like

   Date newDate = convert(currentDate, currentFormatString, newFormatString).

How can I do it?

Council answered 22/10, 2014 at 5:13 Comment(0)
O
27

You should look into momentjs, which is a javascript date/time library. With that, you can easily convert between dates of different format. In your case, it would be:

string newDate = moment(currentDate, currentFormatString).format(newFormatString)

For example, moment("21/10/14", "DD/MM/YY").format("MM/DD/YY") would return "10/21/14"

Orangery answered 22/10, 2014 at 5:21 Comment(2)
var newDate = moment("Nov/21/2015", "mmm/DD/YYYY").format("MM/DD/YYYY");alert(newDate); -- This does not work.Nonah
^ mmm/DD/YYYY is not a valid format, you're looking for: var newDate = moment("Nov/21/2015", "MMM/DD/YYYY").format("MM/DD/YYYY");alert(newDate);Orangery
L
3

You can use the above described answer of momnet.js or the function below for splitting and using it

For using moment.js make sure you enter your old and new format in upper case

function parseDate(strDate) {

    var dateFormat = $('#currentDateFormat').val();

    var str;
    var res;

    var strFormat = dateFormat.split('.');
    if (strFormat.length != 3)
        strFormat = dateFormat.split('/');
    if (strFormat.length != 3)
        strFormat = dateFormat.split('-');

    str = strDate.split('.');
    if (str.length != 3)
        str = strDate.split('/');
    if (str.length != 3)
        str = strDate.split('-');


    if (strFormat[0].substr(0, 1) == 'd' && strFormat[1].substr(0, 1) == 'M' &&             
        strFormat[2].substr(0, 1) == 'y') // for dd MM yyyy
        res = new Date(str[2], str[1], str[0]);

    if (strFormat[0].substr(0, 1) == 'M' && strFormat[1].substr(0, 1) == 'd' &&
        strFormat[2].substr(0, 1) == 'y') // for MM dd yyyy
        res = new Date(str[2], str[0], str[1]);

    if (strFormat[0].substr(0, 1) == 'y' && strFormat[1].substr(0, 1) == 'M' &&
        strFormat[2].substr(0, 1) == 'd')
        res = new Date(str[0], str[1], str[2]);

    if (strFormat[0].substr(0, 1) == 'y' && strFormat[1].substr(0, 1) == 'd' &&         
        strFormat[2].substr(0, 1) == 'M')
        res = new Date(str[0], str[2], str[1]);

    return res;
}
Loco answered 4/1, 2017 at 11:31 Comment(0)
I
1

You can use the function below

console.log(changeDateFormat('12/1/2020','dd/MM/yyyy','MM/dd/yyyy'));

function changeDateFormat(value, inputFormat, outputFormat) {

let outputSplitter = "/";
let strOutputFormat = outputFormat.split(outputSplitter).map(i => i.toUpperCase());
if (strOutputFormat.length != 3) {
  strOutputFormat = outputFormat.split('-');
  outputSplitter = '-';
}

if (strOutputFormat.length != 3) throw new Error('wrong output format splitter :(');

let date = null;

if (value instanceof Date) {
  date = {
    ["YYYY"]: value.getUTCFullYear(),
    ["MM"]: value.getMonth() + 1,
    ["DD"]: value.getDate()
  }
}

if (typeof value == 'string') {
  let inputSplitter = "/";

  var strInputFormat = inputFormat.split(inputSplitter).map(i => i.toUpperCase());
  if (strInputFormat.length != 3) {
    strInputFormat = inputFormat.split('-');
    inputSplitter = '-';
  }

  if (strInputFormat.length != 3) throw new Error('wrong input format splitter :(');

  let dateElements = value.split(inputSplitter);
  if (dateElements.length != 3) throw new Error('wrong value :(');

  date = {
    [strInputFormat[0]]: dateElements[0],
    [strInputFormat[1]]: dateElements[1],
    [strInputFormat[2]]: dateElements[2],
  }
}

if (!date) throw new Error('unsupported value type:(');

let result = date[strOutputFormat[0]] + outputSplitter
  + date[strOutputFormat[1]] + outputSplitter 
  + date[strOutputFormat[2]];

return result;
 }
Italianism answered 14/4, 2020 at 15:0 Comment(0)
C
0

It seems that you should use the library of query-dateformat git hub for jquery-dateformat
or you can use the normal function like date-time-formate, use the library to config the formate template

Cession answered 22/10, 2014 at 5:20 Comment(3)
I can't understand how to use jquery-dateformat for what I need. How does the convert function knows what's the current format?Council
JavaScript/or any third party lib cant know the format of your date string unless you specify it(if third party support so). It will assume it is in "mm/dd" format i.e month appears before day.Apograph
So it does not answer my problem. I need a function that I can set the current format.Council
A
0

if you use jQuery datepicker you can use something like this one

$.datepicker.formatDate("dd/mm/yy", $.datepicker.parseDate("mm/dd/yy", "11/28/2023"));

answer will be "28/11/2023"

Armallas answered 13/12, 2023 at 14:8 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.