2017-04-06 44 views
0

如果日期爲2017-03-30,我想從2017-03-23日取到2017-03-30如何最近七天特定日期取

我嘗試使用這個代碼讓我String變化Date格式

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 

Date dateParse = sdf.parse("2017-03-30"); 

然後我堅持,因爲我走的參考是獲取當前時間這樣

Calendar c = Calendar.getInstance(); 
c.add(Calendar.DATE, -7); 
//may be my dateParse should put here , but i don't know how to do 
Date monday = c.getTime();//it get the current time 
String preMonday = sdf.format(monday); 

任何人都可以教我如何獲取這七天嗎?提前致謝。

+0

檢查我的回答低於 –

回答

1

解析日期:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
Date myDate = sdf.parse("2017-03-30"); 

首個解決方案1),然後要麼找出你需要多少毫秒減去:

Date newDate = new Date(myDate.getTime() - 604800000L); // 7 * 24 * 60 * 60 * 1000 

二方案二)或使用該提供的API java.util.Calendar中的類:

Calendar calendar = Calendar.getInstance(); 
calendar.setTime(myDate); 
calendar.add(Calendar.DAY_OF_YEAR, -7); 
Date newDate = calendar.getTime(); 

然後,如果需要,將其轉換回一個字符串:

String date = dateFormat.format(newDate); 

這個答案是從here

編輯: 如果需要輸出爲2017年3月29日2017年3月28日2017年3月27日...... 2017年3月23日然後嘗試下面的代碼

for(int i = 1; i <= 7; i++){ 
    Calendar calendar = Calendar.getInstance(); 
    calendar.setTime(myDate); 
    calendar.add(Calendar.DAY_OF_YEAR, -i); 
    Date newDate = calendar.getTime(); 
    String date = dateFormat.format(newDate); 
    //here in date you can get all date from and output as 2017-03-29 2017-03-28 2017-03-27 ...... 2017-03-23 
} 

希望你需要這個

+0

感謝您的信息,但我對變量newDate感到困惑。有兩個newDate,newDate用於'String date = dateFormat.format(newDate);'? –

+0

我嘗試第一個newDate,結果日期是'2017-03-23',我只是得到一天,我可以得到七天嗎? –

+0

檢查我編輯的答案bro。有兩種解決方案請檢查。如果您有任何問題請隨意提問我會幫您@徐博俊 –

2

您可以使用下面

代碼
+0

謝謝你,但你的代碼就像我的問題,日期是當前日期不是我的具體日期。 –

+0

這可以幫助你獲得當前日期 String currentDateTimeString = DateFormat.getDateTimeInstance()。format(new Date()); –

+0

感謝您的熱情,我現在得到解決方案,謝謝。 –