在 JavaScript 中将日期从一种格式转换为另一种格式 [英] Convert Date from one format to another format in JavaScript
问题描述
我在 javascript 中有一个日期字符串,格式为 #1.我需要将其转换为格式 #2.
I have a string of a date in javascript in format #1. I need to convert it to format #2.
当一种格式是dd/mm/yy"而另一种格式是mm/dd/yy"时,问题就开始了.
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).
我该怎么做?
推荐答案
你应该研究 momentjs,这是一个javascript 日期/时间库.有了它,您可以轻松地在不同格式的日期之间进行转换.在您的情况下,它将是:
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)
例如,moment("21/10/14", "DD/MM/YY").format("MM/DD/YY")
将返回 10/21/14"
这篇关于在 JavaScript 中将日期从一种格式转换为另一种格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!