簡體   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