简体   繁体   English

如何将日期时间格式转换为JavaScript中的另一种格式?

[英]How to convert date time format to another format in javascript?

I have a date time string like this 我有这样的日期时间字符串

8/14/2015 7:26 AM , for example, in javascript how can I convert that to this format March 30, 2015 11:31 AM ? 例如March 30, 2015 11:31 AM 8/14/2015 7:26 AM在javascript中如何将其转换为这种格式March 30, 2015 11:31 AM

Thanks 谢谢

Can't see any reason to use an external library for what is just a few lines of code. 仅仅几行代码就看不到使用外部库的任何理由。 Playing around in the console can be good for things like this, since Chrome at least, will show you the available methods that an object has, saving you much time researching MDN/w3schools. 在控制台中玩耍可能对诸如此类的事情有好处,因为至少Chrome会向您显示对象具有的可用方法,从而节省了许多研究MDN / w3schools的时间。

Eg type var tmp = new Date(); 例如,类型var tmp = new Date(); into the console. 进入控制台。 Now, type tmp. 现在,键入tmp. and you should see a massive drop-down list of the methods that a Date object has. 并且您应该看到Date对象具有的方法的巨大下拉列表。

Anyway, to solve the problem you present you may use code of the following form. 无论如何,要解决您提出的问题,您可以使用以下形式的代码。 I've not done any error-checking, that's left as an exercise for the reader. 我没有进行任何错误检查,这留给读者练习。

function dateTest()
{
    var initialDateStr = "8/14/2015 7:26 AM";
    var months = ['January', 'February', 'March', 'April', 'May', 'June',
                  'July', 'August', 'Setember', 'October', 'November', 'December'];

    var dateObj = new Date(initialDateStr);

    var outputString = months[ dateObj.getMonth() ] + ' ';
    outputString += dateObj.getDate() + ', ';
    outputString += (dateObj.getYear()+1900) + ' ';

    var hrs12 = dateObj.getHours();
    if (hrs12 > 13)
        outputString += (hrs12-12) + ':';
    else
        outputString += (hrs12) + ':';

    outputString += dateObj.getMinutes() + ' ';

    if (hrs12 > 11)
        outputString += 'PM';
    else
        outputString += 'AM';

    console.log( outputString );
    //August 14, 2015 7:26 AM
}

您可以在此处找到用于此方案的外部开源库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM