user10091301
user10091301

Reputation:

Convert From One date format to other gives invalid date

I want to convert a date from 18/04/2019 13:17:41 to 18-04-2019 13:17:41 ie from DD/MM/YYYY HH:MM:SS to DD-MM-YYYY HH:MM:SS. I have tried moment js and Date function () but they either return null or invalid date ,where I am wrong here ? Any help will be appreciated

let str="18/04/2019 13:17:41";
let strf=str.replace(/[/]/g,"-");
console.log(strf)
let date=moment(strf,"DD-MM-YYYY HH:MM:SS").format("DD-MM-YYYY HH:MM:SS");
console.log(date)
console.log(new Date("18/04/2019 13:17:41")) // gives null
console.log(new Date("18-04-2019 13:17:41")) // gives null
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>

Upvotes: 0

Views: 1148

Answers (2)

Manjunath M
Manjunath M

Reputation: 608

Your trying to convert string of format "DD-MM-YYYY HH:mm:ss" to moment date. Which is not supported by momentjs. Here are supported string formats which you can convert to moment date.

2013-02-08               # A calendar date part
2013-W06-5               # A week date part
2013-039                 # An ordinal date part

20130208                 # Basic (short) full date
2013W065                 # Basic (short) week, weekday
2013W06                  # Basic (short) week only
2013050                  # Basic (short) ordinal date

2013-02-08T09            # An hour time part separated by a T
2013-02-08 09            # An hour time part separated by a space
2013-02-08 09:30         # An hour and minute time part
2013-02-08 09:30:26      # An hour, minute, and second time part
2013-02-08 09:30:26.123  # An hour, minute, second, and millisecond time part
2013-02-08 24:00:00.000  # hour 24, minute, second, millisecond equal 0 means next day at midnight

20130208T080910,123      # Short date and time up to ms, separated by comma
20130208T080910.123      # Short date and time up to ms
20130208T080910          # Short date and time up to seconds
20130208T0809            # Short date and time up to minutes
20130208T08              # Short date and time, hours only

Upvotes: 0

jonatjano
jonatjano

Reputation: 3728

js Date use a YYYY-MM-DD format

let str="2019/04/18 13:17:41";

console.log(new Date(str)) // works

you can use something like this to convert from DD/MM/YYYY to YYYY/MM/DD but the best would be to get the date in the right format from the start

let str="18/04/2019 13:17:41";

str = str.split(" ").map(part => part.split("/").reverse().join("/")).join(" ")

console.log(str)
console.log(new Date(str))

Upvotes: 1

Related Questions