2010-02-28 31 views
1

我有一個包含月份/日期的字符串,我需要插入年份。該字符串的樣子:JavaScript日期:如何將一年添加到包含mm/dd的字符串中?

Last Mark:: 2/27 6:57 PM 

我想將字符串轉換爲類似:

Last Mark:: 2010/02/27 18:57 

在這種情況下,不會有任何條目一年多歲。例如,如果日期是10/12,那麼可以假設該年是2009年。

對此的最佳方法是什麼?

回答

2

Adam's suggestion以下:

function convertDate(yourDate) { 
    var today = new Date(); 
    var newDate = new Date(today.getFullYear() + '/' + yourDate); 

    // If newDate is in the future, subtract 1 from year 
    if (newDate > today) 
     newDate.setFullYear(newDate.getFullYear() - 1); 

    // Get the month and day value from newDate 
    var month = newDate.getMonth() + 1; 
    var day = newDate.getDate(); 

    // Add the 0 padding to months and days smaller than 10 
    month = month < 10 ? '0' + month : month;  
    day = day < 10 ? '0' + day : day; 

    // Return a string in YYYY/MM/DD HH:MM format 
    return newDate.getFullYear() + '/' + 
      month + '/' + 
      day + ' ' + 
      newDate.getHours() + ':' + 
      newDate.getMinutes(); 
} 

convertDate('2/27 6:57 PM'); // Returns: "2010/02/27 18:57" 
convertDate('3/27 6:57 PM'); // Returns: "2009/03/27 18:57" 
+0

+1大大簡化 – 2010-02-28 15:49:07

+0

現在,它不太簡單,但功能更強大和更小容易出錯:D GW – 2010-02-28 16:08:52

+0

@Adam:嘿嘿......至少我已經在那裏撒了一些評論:) – 2010-02-28 16:13:56

0

這將返回本年度:

var d = new Date(); 
var year = d.getFullYear(); 

到今年數字是否它與否,你可以只比較日期和月份與當前的日期和月份,並在必要時,從當年減去1。

要獲得日期和月份從Date對象:

d.getMonth(); // warning this is 0-indexed (0-11) 
d.getDate(); // this is 1-indexed (1-31) 
1

添加年代碼簡單

var d = Date(); 
var withYear = d.getFullYear() + yourDate; 

然而,背後considerating如果它應該是這樣的邏輯年或去年可能會更難做

我會這樣想:得到今天的日期。如果日期是比今天的高,這是去年,所以加d.getFullYear()-1,否則添加d.getFullYear()

相關問題