简体   繁体   English

将字符串转换为数组中的日期对象

[英]Convert String to Date Object in Array

I have a table which has a date string in the header. 我有一个表,表头中有一个日期字符串。 It is returned as part of an array but I need that date in the array to be a Date Object and not just a string. 它作为数组的一部分返回,但我需要数组中的该Date Object成为Date Object ,而不仅仅是一个字符串。

My table is as follows 我的桌子如下

DEMO DEMO

// [[20th Jan, 33], [21st Jan, 44], [22nd Jan, 5],[23rd Jan, 17]]

I use the following JS to get this array 我用下面的JS来获得这个数组

var arr = $.map($('#bookedTable th:not(:first)'), function(el,i) {
    return [[$(el).text(), $('#bookedTable td:eq('+i+')').text()]]
});

console.log(arr)

Question: How can I return the string dates as date objects in my array? 问题:如何将字符串日期作为数组中的日期对象返回?

You need to ran something like this function on all your dates in array :) 您需要在数组中的所有日期上运行类似此功能的东西:)

function parseThisDate(date) {
  dateParts = date.split(" ");

  return new Date(dateParts[2], translateMonthToNum(dateParts[1]), dateParts[0])
}

function translateMonthToNum(monthName) {
  if (monthName == 'Jan,') return 0;
  //todo: add all months you need
}

You can always convert a string to date as 您始终可以将字符串转换为date为

var myDate = new Date("2013/1/16"); var myDate = new Date(“ 2013/1/16”);

You can clearly get the "2013/1/16" from the array provided the months are in numbers. 您可以清楚地从数组中获取“ 2013/1/16”,前提是月份为数字。

click here for more info on date object in JavaScript. 单击此处以获取有关JavaScript中日期对象的更多信息。

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

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