2017-08-16 95 views
-2

這是我的Java代碼查找當前月/日,我們在:如何在Java中查找當前月份長度?

import java.text.DateFormat; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

public class GetCurrentDateTime { 

private static final DateFormat sdf = new SimpleDateFormat("MM-dd"); 


public static void main(String[] args) { 

    Date date = new Date(); 
    System.out.println(sdf.format(date)); 

    } 
} 

我想這個代碼到別的做一些事情。當代碼找到我們所在的月份時,我也希望它找到月份的長度。結果應該是這樣的:

08-16 
31 

你能幫我嗎?謝謝。

+2

肯定。我們很樂意幫助你。但只有當我們看到你已經盡力解決這個問題。 –

+0

@TAsk對於Stack Overflow的所有問題,這不是必需的。 –

+4

可能重複[特定年份的特定月份的天數?](https://stackoverflow.com/questions/8940438/number-of-days-in-particular-month-of-particular-year) – Lemonov

回答

1

你可以嘗試這樣的事情,但我認爲,有可能是一個更好的辦法:

Date date = new Date(); 
System.out.println(sdf.format(date)); 
Calendar c = Calendar.getInstance(); 
c.setTime(date); 
System.out.println(c.getActualMaximum(Calendar.DAY_OF_MONTH)); 

輸出是這樣的:

08-16 
31 

編輯:
作爲寫在評論:

使用從羅勒YearMonth.now().lengthOfMonth()解決方案,這是一個更好的方法比這

+0

使用Basil'YearMonth.now().lengthOfMonth()'的解決方案,這是一個比這更好的方法。 – StefanPG

+0

真的,是時候把這個'Calendar'類放在一個盒子裏,然後把它放在閣樓後面,以便被忽略和遺忘。 –

+0

對我感到羞恥,當我寫解決方案時,我甚至不知道ZoneId/YearMonth。但你是對的,這是一個更好,更清晰的方式。 – StefanPG

4

TL;博士

YearMonth.now() 
     .lengthOfMonth() 

詳細

避免在看到問題的麻煩舊日期時間類。現在由java.time類取代。

時區對確定今天的日期以及確定當前月份至關重要。對於任何特定的時刻,日期在全球各地按照地區而不同。

ZoneId z = ZoneId.of("America/Montreal") ; 
YearMonth ym = YearMonth.now(z) ; 
int daysInMonth = ym.lengthOfMonth() ; 
0

也許是:

@Test 
    public void daysOfMonthTest() throws Exception { 
    Calendar mycal = new GregorianCalendar(); 

    assertEquals(
      31, 
      mycal.getActualMaximum(Calendar.DAY_OF_MONTH)); 
    } 
0

注:月是0(一月)到11(月)編號。

使用簡單的Date對象:

 Date date = new Date(); 
     int month = date.getMonth() + 1; 
     int year = date.getYear()+1900; 
     System.out.print(month+"-"+year); 

輸出:

8-2017 

使用日曆對象:

 Date date = new Date(); // your date 
    Calendar cal = Calendar.getInstance(); 
    cal.setTime(date); 
    int year = cal.get(Calendar.YEAR); 
    int month = cal.get(Calendar.MONTH); 
    int day = cal.get(Calendar.DAY_OF_MONTH) + 1; 
    System.out.print(month+"-"+year); 
    System.out.print("Number of days: "+cal.getActualMaximum(Calendar.DAY_OF_MONTH)); 

輸出:

8-2017 
Number of days: 31 

使用JodaTime:

DateTime dateTime = new DateTime(); 
    System.out.print(dateTime.getMonthOfYear()+"-"+(dateTime.getYear())); 
    System.out.print("Number of days: "+ dateTime.dayOfMonth().getMaximumValue()); 

輸出:

8-2017 
Number of days: 31 
+1

這是如何顯示當月的天數? –

+0

@ScaryWombat更新,請檢查 –

相關問題