2017-04-16 64 views
1

我有像这样的JSON中的数据 - 19-04-2017T12:40:00,这是日期值,我想要在“T”之前的部分并想要转换这个值并得到日期结构,例如2017年4月25日星期三。如何在javascript中实现这个?我想在日期字符串T之前有一个字符串

+2

momentjs是解析日期的好库 –

回答

1

如果你可以使用外部库,那么momentjs是最好的之一。

var data = { 
    "selectedOnwardFlight": [ 
     { 
      "lstExtraServices": [], 
      "flightDuration": "1:20", 
      "departuretime": "19-04-2017T12:40:00", 
      "arrivalairport": "GOI_Dabolim, Goa", 
      "segment": 1, 
      "departureairport": 
      "BOM_Chhatrapati Shivaji International, Mumbai", 
      "mac": "6E_Indigo Airlines", 
      "fno": "5924", 
      "dpartTerInfo": "1", 
      "oac": "6E", 
      "arrivaltime": "19-04-2017T14:00:00", 
      "arrivalTerInfo": "" 
     } 
    ] 
} 

var date = moment(data.selectedOnwardFlight[0].arrivaltime, "DD-MM-YYYYThh:mm:ss") 
// You need to specify input date format 

console.log(date.format("ddd, DD, MMM, YYYY")) 
// After creating moment date object, you can get date in almost any format. 

给人星期三,19月,2017年

详细解析和输出格式,检查momentjs docs

+0

必须将此值19-04-2017T12:40:00转换为字符串才能将其作为参数在时间传递? – SmitSherlock

+0

因为我从JSON得到这个值19-04-2017T12:40:00因为它没有双引号 – SmitSherlock

+0

是的,它必须是字符串。如果你从json获得价值,它应该是字符串,我猜。你可以发布示例数据吗? –

1

您可以使用new Date()String.prototype.slice()与参数010"-"作为参数,Array.prototype.reverse().join()与参数"/"与参数0得到字符"T".split(),再次.slice()15获得所需的日期部分

var date = String(
 
      new Date("19-04-2017T12:40:00".slice(0, 10) 
 
      .split("-").reverse().join("/")) 
 
      ).slice(0, 15); 
 

 
console.log(date);

0

使用时刻JavaScript库,并在下面的功能

通过你的JSON值
function formatDate(jValue) { 
     var l = jValue.split("T")[0].split("-"); 
     var r = l[2] + "-" + l[1] + "-" + l[0]; 
     var o = moment(r); 
     return o.format("LLLL").split(',')[0].trim() + ", " + o.date() + " " + o.format("lll").split(",")[0].split(" ")[0].trim() + ", " + o.year() 
    } 

提供“19-04-2017T12:40:00”作为参数o/p是2017年4月19日星期三

相关问题