繁体   English   中英

取出日期年份并用Java转换月份

[英]Take Out the Year of Date and Convert Month in Javascript

我正在使用

$this(find).text() 

在Javascript中解析XML。

在HTML中运行时,XML中文本的日期输出如下所示:

2014-04-07T19:48:00

我正在尝试使其成为:

April 7 19:48 (no years).

我该怎么办? this.find.text()很难弄清楚。 substr()已用于获取年份,但我需要将月份转换为字符串,例如04到April。

这是用于从解析的XML生成的随机日期。 不只是一天。

您可以在javascript中创建Date对象:

var x = new Date("2014-04-07T19:48:00");

并在该对象上调用此页面上的所有函数:

http://www.w3schools.com/jsref/jsref_obj_date.asp

您将基本上需要使用“月”构建一个数组。 然后,您将使用Date对象属性.getMonth() ,然后将输出一个数字,该数字是您需要数组的时间:

function formatDate (dateFromXmlDoc) {    
var theDate = new Date(dateFromXmlDoc);
var theMonth = theDate.getMonth(); //returns 3


var monthArray = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "November", "December"];
return monthArray[theMonth]; //Outputs 'April'
}

之后,您可以将日期格式构建为所需的格式

function convertDate(date) {
  // array with month names
  months = [
    "January", "February", "March",
    "April", "May", "June",
    "July", "August", "September",
    "October", "November", "December"
  ];

  // Since date is in ISO 8601 format, we can count on
  // positions of parts of the date within the string;
  // if this were not true, we'd rather use the less
  // efficient but more robust 'split' method to get
  // the date parts.
  // Also, we must convert zero-prefixed strings to
  // integers, and look-up the month string in the array.
  // One might be tempted to use the "new Date(date)" to
  // get a date object, but it is too smart for our purposes,
  // as it takes the time-zone into account.
  return months[parseInt(date.substr(5, 2))-1] + " " 
        + parseInt(date.substr(8, 2)) + " "
        + date.substr(11, 5);
}

convertDate("2014-11-12T04:48:00");

暂无
暂无

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

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