![](/img/trans.png)
[英]How to get the day of week for a given date when the week begins on a Monday?
[英]How to get the next week monday date from user input date in java
我是一名新學習Java的在校學生!
我的情況是:*從用戶處獲取輸入日期*向用戶顯示下周的星期一日期,以o / p的形式顯示!
例如,輸入日期:15/12/2016輸出:19/12/2016(星期一)
我搜索了論壇,並獲得了下面的代碼。
GregorianCalendar date1 = new GregorianCalendar( 2016, 12, 12 );
while( date1.get( Calendar.DAY_OF_WEEK ) != Calendar.MONDAY )
date1.add( Calendar.DATE, 1 );
System.out.println(date1.getTime());
但這給了我o / p 2017年1月16日星期一格林尼治標准時間+05:30,代表2016年12月12日i / p。
我想在2016年12月19日獲得o / p。 請幫助我的技術天才!
使用SimpleDateFormat
格式化日期
注意GregorianCalendar mounth它從0開始
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY");
System.out.println(sdf.format(date1.getTime()));
它很好地說明了GregorianCalendar( 2016, 12, 12 )
意思
2017/12/01
您的代碼正常工作。 您必須將月份設為0-11(1月-12月)。 請嘗試以下修改的代碼:
GregorianCalendar date1 = new GregorianCalendar( 2016, 11, 13 ); // here month start for 0 to 11 (Jan to Dec.)
while( date1.get( Calendar.DAY_OF_WEEK ) != Calendar.MONDAY )
date1.add( Calendar.DATE, 1 );
System.out.println(date1.getTime());
謝謝...
您可以簡化代碼:
GregorianCalendar date1 = new GregorianCalendar( 2016, 11, 16 );
date1.add(Calendar.DATE, 7); //Move to next weed
date1.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); //Set the day to Monday of current week
LocalDate.parse(
"15/12/2016" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" )
).with(
TemporalAdjusters.next( DayOfWeek.MONDAY )
)
您正在使用麻煩的舊日期時間類(現在已遺留),由java.time類取代。
LocalDate
LocalDate
類表示沒有日期和時區的僅日期值。
LocalDate ld = LocalDate.parse( "15/12/2016" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) );
java.time類使用不可變對象 。 因此,我們無需更改(“突變”)現有對象中的值,而是根據原始對象的值實例化一個新對象。 一種實現方法是使用TemporalAdjuster
的實現。
LocalDate nextMonday = ld.with( TemporalAdjusters.next( DayOfWeek.MONDAY ) ) ;
這些課程已經討論了很多次。 因此,搜索堆棧溢出以獲取更多信息。
java.time框架內置於Java 8及更高版本中。 這些類取代了麻煩的舊的舊式日期時間類,例如java.util.Date
, Calendar
和SimpleDateFormat
。
現在處於維護模式的Joda-Time項目建議遷移到java.time類。
要了解更多信息,請參見Oracle教程 。 並在Stack Overflow中搜索許多示例和說明。 規格為JSR 310 。
在哪里獲取java.time類?
如果查看GregorianCalendar的JavaDoc,您可能會看到所使用的構造函數的month參數從1月份的0開始,因此12 月份的參數為11 。
然后將12解釋為2017年 1 月 ,這意味着16/01/2017是正確的結果。
感謝你的幫助! 經過一個小時的編碼,我通過以下代碼實現了它! 請檢查代碼,如果我不在某個地方,請與我聯系!
GregorianCalendar date1 = new GregorianCalendar( year, month-1, date );
SimpleDateFormat dateOnly = new SimpleDateFormat("dd/MM/yyyy");
// System.out.println("Formated date"+dateOnly.format(date1.getTime()));
String day1="",day2;
while( date1.get( Calendar.DAY_OF_WEEK ) != Calendar.MONDAY )
date1.add( Calendar.DATE, 1 );
da1=String.valueOf(dateOnly.format(date1.getTime()));
System.out.println("Start_date"+da1);
date1.add(Calendar.DATE, 6);
da2=String.valueOf(dateOnly.format(date1.getTime()));
System.out.println("End_date"+da2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.