将日期yyyy / mm / dd转换为MM dd yyyy

时间:2014-08-28 14:27:59

标签: javascript

我在JavaScript中使用日期yyyy / mm / dd格式,我想在文本框中显示它 格式示例:2014年1月1日。

function displayinTextbox(){
          var datetodisplay = new Date('2014/01/01'); //i want to convert it first in this format (January 1 2014)
          var convertedDate = ///how??????
          document.getElementById('date').value = convertedDate ;
}

5 个答案:

答案 0 :(得分:2)

function displayinTextbox(){
    var datetodisplay = new Date('2014/01/01');
    var months = ["January", "February", "March", "April", "May", "June", "July", August", "September", "October", "November", "December"];
    var convertedDate = months[datetodisplay.getMonth()] + " " + datetodisplay.getDate() + " "+datetodisplay.getUTCFullYear();
    document.getElementById('date').value = convertedDate ;
}

答案 1 :(得分:1)

试试这个:

function displayinTextbox(){
    var datetodisplay = new Date('2014/01/01');
    var convertedDate = datetodisplay.toDateString();
    document.getElementById('date').value = convertedDate ;
}

答案 2 :(得分:0)

getDate(): Returns the day of the month.
getDay(): Returns the day of the week. The week begins with Sunday (0 - 6).
getFullYear(): Returns the four-digit year.
getMonth(): Returns the month.
getYear(): Returns the two-digit year.
getUTCDate(): Returns the day of the month according to the Coordinated Universal Time (UTC).
getUTCMonth(): Returns the month according to the UTC (0 - 11).
getUTCFullYear(): Returns the four-digit year according to the UTC.

Read this article

答案 3 :(得分:0)

Date对象提供various methods来访问制作日期/时间数据的不同部分。

在您的情况下,将月份显示为名称而不是数字需要将月份值(从0到11)映射到月份名称(从" 1月和#34;到" 12月和#34 ;)

var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var convertedDate = monthNames[dateToDisplay.getMonth()] + " " + dateToDisplay.getDate() + " " + "dateToDisplay.getFullYear();

如果你必须处理多种语言并且"漂亮"格式,您可能需要查看格式库,例如Moment.js

答案 4 :(得分:0)

我建议您使用Moment.js库。

你需要的东西可以简单地用Moment.js完成。

var str = '2014/01/01';
var formatted = moment(str, 'YYYY/MM/DD').format('MMMM D YYYY');
console.log(formatted);

http://jsfiddle.net/949vkvjk/2/