2015-07-06 51 views
1

我需要格式化日期字符串的幫助。我有一個包含元素「start_date」和「end_date」的JSON對象。這些元素包含字符串中的日期信息,比如這樣:Ruby函數來格式化日期

"2015-07-15" 

我創造了這個方法格式化我的起始日期日期和結束日期:

def format_date(date) 
    date.to_time.strftime('%b %d') 
end 

什麼這個方法確實是日期格式爲這種格式的:

"Jul 15" 

這種方法可以幫助我打印起始日期日期和結束日期到表單:

"Jul 15 to Jul 27" 

我想要什麼,是有我的日期的形式格式化:

"15 - 27 July 2015" #If the two dates fall within the same month 

"15 July - 27 Aug 2015" #If the two dates fall into separate months 

誰能幫助我寫這樣一個紅寶石方法?

+4

我認爲你必須在這裏處理幾種情況:(1)同一天,( 2)不同的日子,但相同的月份和年份,(3)不同的月份,但同年(4)不同的年份。 – Stefan

回答

1

你的意思是這樣的嗎?

def format_date(date1, date2) 

    # convert the dates to time 
    date1 = date1.to_time 
    date2 = date2.to_time 

    # Ensure date1 is the lowest 
    if date1 > date2 
    date1, date2 = date2, date1 
    end 

    # handle identical dates 
    if date1 == date2 
    return date1.strftime('%d %b %Y') 
    end 

    # handle same year 
    if date1.year == date2.year 

    #handle same month 
    if date1.month == date2.month 
     return "#{date1.strftime('%d')} - #{date2.strftime('%d %b %Y')}" 

    # handle different month 
    else 
     return "#{date1.strftime('%d %b')} - #{date2.strftime('%d %b %Y')}" 
    end 
    end 

    # handle different date-month-year 
    return "#{date1.strftime('%d %b %Y')} - #{date2.strftime('%d %b %Y')}" 
end 

我會從此開始,並將其重構爲更易讀易用的東西。

+0

謝謝百萬老兄!你幾乎救了我幾個小時,破壞了我的大腦!對此,我真的非常感激!再次感謝! – NdaJunior