我是JavaScript的新手(但不是编程人员),并且很难弄清楚我在此函数中的错误之处,可在以下位置找到:http://mikeryan.webatu.com/function.html [死链接] [猜测底部的原始代码]

该函数应采用DDMMYY时间戳并将其转换为人类可读的字符串。例如,210710将变成July 21st, 2010

更新:可能与OP的死链接类似的代码:

function timestamp(d){
    var year = (d-(Math.round(d / 100)*100);

    var day = Math.floor(d/10000);
    var dayfix = (day - (Math.floor(day/10)*10));

    // var month = ((d-year)-(day*100000)/100);

    var a = (d - year);
    var b = ((day * 100000) / 10);

    var month = (a - b) / 100;

    var months = new Array();
    months[1]  = "January";
    months[2]  = "February";
    months[3]  = "March";
    months[4]  = "April";
    months[5]  = "May";
    months[6]  = "June";
    months[7]  = "July";
    months[8]  = "August";
    months[9]  = "September";
    months[10]  = "October";
    months[11] = "November";
    months[12] = "December";

    var daysuffix = new Array();
    daysuffix[0] = "th";
    daysuffix[1] = "st";
    daysuffix[2] = "nd";
    daysuffix[3] = "rd";
    daysuffix[4] = "th";
    daysuffix[5] = "th";
    daysuffix[6] = "th";
    daysuffix[7] = "th";
    daysuffix[8] = "th";
    daysuffix[9] = "th";

    if(year>20){
       year = '19' + year;
    }
    else{
       year = '20' + year;
    }
    return (months[month] + ' ' + day + daysuffix[dayfix] + ', ' + year);
 }

最佳答案

一个问题:您缺少括号。更改:

var year = (d-(Math.round(d / 100)*100);




var year = (d-(Math.round(d / 100)*100));


话虽如此,这是一种更直接的计算方法:

var year = d % 100;
var month = Math.floor(d / 100) % 100;
var day = Math.floor(d / 10000) % 100;


接下来,数组初始化不必要地冗长。代替:

var arr = new Array();
arr[0] = "foo";
arr[1] = "bar";


做就是了:

var arr = ["foo", "bar"];


您的日后缀不正确。它将“ nd”放在12月12日之后,“ 4月12日”显然是不正确的。我只会使用逻辑来执行此操作,而不是使用大多数元素都是“ th”的查找数组。

所以:

function timestamp(d){
  var year = d % 100;
  var month = Math.floor(d / 100) % 100;
  var day = Math.floor(d / 10000) % 100;
  var months = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"];
  if (year>20) {
    year = '19' + year;
  } else {
    year = '20' + year;
  }
  if (day == 1 || day == 21 || day == 31) {
    var suffix = "st";
  } else if (day == 2 || day == 22) {
    var suffix = "nd";
  } else {
    var suffix = "th";
  }
  return (months[month-1] + ' ' + day + suffix + ', ' + year);
}


最后,您的“时间戳”几乎没有任何值,它是当前形式的整数。这类事情更典型的格式是YYYYMMDD,这有两个原因:


数字排序与日期排序匹配;和
这是明确的。北美人日复一日地投放广告(例如MMDDYY)。世界上其他所有人都把第一天(即DDMMYY)放在第一位。没有人做YYDDMM。

关于javascript - 将数字DDMMYY转换为日期?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3296105/

10-12 04:25