【问题标题】:datetime convert to date string - javascript日期时间转换为日期字符串 - javascript
【发布时间】:2016-05-03 06:22:04
【问题描述】:

我在 json 中有以下日期时间值:

Fri Jan 22 2016 14:34:38 GMT-0500

我想显示类似"January 22, 2016"的内容

我怎样才能在 javascript 中实现这一点。我有可用的 JQuery、Extjs 库。

【问题讨论】:

  • 检查moment.js库,然后您可以使用moment("Fri Jan 22 2016 14:34:38 GMT-0500").format("LL")获取格式化日期

标签: javascript jquery json date


【解决方案1】:

在这里找到了这个疯狂的方法,但是有效!

Converting milliseconds to a date (jQuery/JS)

这是我做的小提琴

https://jsfiddle.net/Ripper1992/hj6L2Lvz/

var now = new Date("Fri Jan 22 2016 14:34:38 GMT-0500");
alert(now.customFormat( "#MMMM# #DD#, #YYYY#" ) );

customFormat是根据#MMMM##DD#获取Data各部分、解析替换的函数或 #SS# 由用户定义。

这是带有文档的完整功能 http://phrogz.net/JS/FormatDateTime_JS.txt

【讨论】:

    【解决方案2】:

    这个问题是针对你的同一个问题。您可以根据需要使用此处显示的函数来构造日期字符串。

    // This could be any Date String
    var str = "Fri Feb 08 2013 09:47:57 GMT +0530 (IST)";
    var date = new Date(str);
    

    这将使您可以访问所有日期函数 (MDN)

    例如:

    var day = date.getDate(); //Date of the month: 2 in our example
    var month = date.getMonth(); //Month of the Year: 0-based index, so 1 in our example
    var year = date.getFullYear() //Year: 2013
    

    Extract date and time from string using Javascript

    【讨论】:

    • @JohnHascall 抱歉,这是新手。下次会记得的。谢谢!
    • 别担心,我们都是新人。
    【解决方案3】:

    尝试使用for..in循环、String.prototype.slice()String.prototype.replace()创建具有缩写月份属性、整月值的对象

    var months = {
     "Jan":"January",
      "Feb":"February",
      "Mar":"March",
      "Apr":"April",
      "May":"May",
      "Jun":"June",
      "Jul":"July",
      "Aug":"August",
      "Sep":"September",
      "Oct":"October",
      "Nov":"November",
      "Dec":"December"
    };
    
    var date = "Fri Jan 22 2016 14:34:38 GMT-0500";
    // extract "Jan 22 2016" from `date`
    var d = date.slice(4, -18);
    
    for (var prop in months) {
      if (new RegExp(prop).test(d)) {
        // replace abbreviated month with full month name
        d = d.replace(prop, months[prop]);
        // replace day with day followed by comma `,` character
        d = d.replace(/(\d{2})(?=\s)/, "$1,")
      }
    }
    
    document.body.textContent = d

    【讨论】:

      猜你喜欢
      • 2017-07-29
      • 2015-09-17
      • 1970-01-01
      • 2021-05-31
      • 2019-04-12
      • 2011-09-08
      • 2015-03-24
      • 2011-05-17
      • 1970-01-01
      相关资源
      最近更新 更多