![](/img/trans.png)
[英]Java: How to display weekday, month and date and no year in locale sensitive manner
[英]How to display date of a current month with the month and year in Java?
如何在Java中動態顯示for循環中特定月份的日期,月份和年份?
另一個答案使用麻煩的舊日期時間類(現已遺留),由java.time類取代。
LocalDate
LocalDate
類表示沒有日期和時區的僅日期值。
時區對於確定日期至關重要。 在任何給定時刻,日期都會在全球范圍內變化。 例如, 法國巴黎午夜過后幾分鍾是新的一天,而在魁北克蒙特利爾仍然是“昨天”。
以continent/region
的格式指定正確的時區名稱 ,例如America/Montreal
, Africa/Casablanca
或Pacific/Auckland
。 切勿使用EST
或IST
等3-4個字母的縮寫,因為它們不是真實的時區,不是標准化的,甚至不是唯一的(!)。
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
YearMonth
我們關心整個月。 因此,使用YearMonth
對象來表示該對象。
YearMonth ym = YearMonth.from( today );
獲取本月的第一天。
LocalDate localDate = ym.atDay( 1 );
循環播放,一次將日期增加一天,直到月末。 我們可以通過查看每個遞增的日期是否具有與今天相同的YearMonth
來測試該事實。 將每個日期收集在一個List
。
List<LocalDate> dates = new ArrayList<>( 31 ); // Collect each date. We know 31 is maximum number of days in any month, so set initial capacity.
while( YearMonth.of( localDate).equals( ym ) ) { // While in the same year-month.
dates.add( localDate ); // Collect each incremented `LocalDate`.
System.out.println( localDate );
// Set up next loop.
localDate = localDate.plusDays( 1 );
}
java.time框架內置於Java 8及更高版本中。 這些類取代了麻煩的舊的舊式日期時間類,例如java.util.Date
, Calendar
和SimpleDateFormat
。
現在處於維護模式的Joda-Time項目建議遷移到java.time類。
要了解更多信息,請參見Oracle教程 。 並在Stack Overflow中搜索許多示例和說明。 規格為JSR 310 。
在哪里獲取java.time類?
ThreeTen-Extra項目使用其他類擴展了java.time。 該項目為將來可能在java.time中添加內容提供了一個試驗場。 您可以在這里找到一些有用的類,比如Interval
, YearWeek
, YearQuarter
,和更多 。
這簡要演示了Java中SimpleDateFormat
和GregorianCalendar
類的一些基礎知識。 根據您的問題,這是我能做的最好的事情。
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
public class Main {
public static void main(String[] args) {
int year = 2012;
int month = 4;
/* The format string for how the dates will be printed. */
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
/* Create a calendar for the first of the month. */
GregorianCalendar calendar = new GregorianCalendar(year, month, 1);
/* Loop through the entire month, day by day. */
while (calendar.get(GregorianCalendar.MONTH) == month) {
String dateString = format.format(calendar.getTime());
System.out.println(dateString);
calendar.add(GregorianCalendar.DATE, 1);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.