I have two dates in Java:
Wed Jan 05 00:00:00 CET 2011
Sat Jan 15 23:59:59 CET 2011
Now I want to iterate over them, so that every day I can do a System.out.println() in which I put the date in this kind on the console:
2011-01-05
2011-01-06
2011-01-07
...
2011-01-13
2011-01-14
2011-01-15
How can I do this?
Best Regards, Tim.
Update:
Calendar calend = Calendar.getInstance();
calend.setTime(myObject.getBeginDate());
Calendar beginCalendar = new GregorianCalendar(calend.get(Calendar.YEAR), calend.get(Calendar.MONTH), calend.get(Calendar.DATE));
calend.setTime(myObject.getEndDate());
Calendar endCalendar = new GregorianCalendar(calend.get(Calendar.YEAR), calend.get(Calendar.MONTH), calend.get(Calendar.DATE));
while (beginCalendar.compareTo(endCalendar) <= 0) {
// ... calculations
beginCalendar.add(Calendar.DATE, 1);
}
Use the GregorianCalendar object to increment one day at a time
Output using SimpleDateFormat.
To get your date from a string, into a Date object, you have to do the following
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date date = format.parse(yourDateString);
Then, you need to convert into a GregorianCalendar, so that you can easily increment the values and finally output the date using another SimplerDateFormat in the way you want to. See the documentation for the different codes.
Update:
Update, following your code update, you can simply do the following
Calendar beginCalendar = Calendar.getInstance();
beginCalendar.setTime(myObject.getBeginDate());
Calendar endCalendar = Calendar.getInstance();
beginCalendar.setTime(myObject.getEndDate());
while (beginCalendar.compareTo(endCalendar) <= 0) {
// ... calculations
beginCalendar.add(Calendar.DATE, 1);
}
Create a Calendar object and set it at the start date. Keep adding a day at a time and printing until you're at the end date.
Related
I would like to set the timepart of a calendar. Here is what I'm doing
Calendar calNow = Calendar.getInstance();
Calendar endWait = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date d1 = null;
try {
d1 = sdf.parse("14:45");
}catch(ParseException ex){
logger.error("Error parsing time");
}
endWait.setTime(d1);
Date waitTo = endWait.getTime();
Date now = calNow.getTime();
The "now" variable is correct date and time, however the waitTo was expected to be the date of today and time 14:45, but is tomorrow at 02:45.
For me it is not giving tomorrow, but waitTo = Thu Jan 01 14:45:00 CET 1970.
The reason for this can be found in the javadoc of SimpleDateFormat:
This parsing operation uses the calendar to produce a Date. All of the
calendar's date-time fields are cleared before parsing, and the
calendar's default values of the date-time fields are used for any
missing date-time information. For example, the year value of the
parsed Date is 1970 with GregorianCalendar if no year value is given
from the parsing operation.
Calendar.setTime() will use the date and time information of the passed Date instance.
To only update the hours and minutes of the waitTo you can:
Calendar tmpCal=Calendar.getInstance();
tmpCal.setTime(d1);
endWait.set(Calendar.HOUR_OF_DAY,tmpCal.get(Calendar.HOUR_OF_DAY));
endWait.set(Calendar.MINUTE, tmpCal.get(Calendar.MINUTE));
This way the day, month, year part of the endWait will not be altered.
I have some data which contains date in different formats, eg: yyyy-dd-MM, yyyy-MM-dd, EEE dd-MM-yy etc.
I am trying to find a way to differentiate between dd-MM-yyyy and MM-dd-yyyy.
I understand that if dd is less than 12, there is no way I can be sure about format, However by identifying other cases when dd > 12, I can minimize the the wrong calculation.
I tried this -
SimpleDateFormat targetFormat = new SimpleDateFormat("EEE, yyyy-MMM-dd hh:mm:ss a");
SimpleDateFormat originalFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat originalFormat2 = new SimpleDateFormat("yyyy-dd-MM HH:mm:ss");
Calendar cal = Calendar.getInstance();
try {
Date date = originalFormat1.parse(s); //I tried with s = "2013-25-8 20:10:00";
cal.setTime(date);
if (cal.get(Calendar.DAY_OF_MONTH) > 12)
date = originalFormat2.parse(s);
System.out.println(targetFormat.format(date));
} catch (ParseException e) {
System.out.println("Error");
Output
I was expecting : Sun, 2013-Aug-25 08:10:00 PM
But I got : Thu, 2015-Jan-08 08:10:00 PM
You can try:
originalFormat1.setLenient(false);
before you try to parse a string with it; that should make it throw a ParseException when the month number is out of range.
When you apply format 1 and it interprets 25 as month then the date starts to become weird, that makes sense as month cannot be bigger than 12. Therefore, your if statement doesn't make sense. You have to check the format before applying the SimpleDateFormat (for instance with Integer.parseInt(s.substring(5,7) > 12).
Hey actually it is taking 25 as month, So 12 + 12 + 1 means 2 years and one month i.e "January"
So, your date becomes : "Thu Jan 08 20:10:00 GMT 2015" and again when you are changing it into "targetFormat" , this unusual result ensues...
I have tried the following; but the results are disappointing.
I want to increment the the months.
String dStartTime="2012-03-01";
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-DD");
Date dateStartTime = dateFormatter.parse(dStartTime);
Calendar cal = Calendar.getInstance();
cal.setTime(dateStartTime);
cal.add(Calendar.MONTH, 1);
System.out.println(cal.getTime());
System.out.println(dateFormatter.format(cal.getTime()));
OUTPUT
Wed Feb 01 00:00:00 IST 2012 --- This is correct
2012-02-32 --- This is wrong. I want the Day should be one.
Please let me know what is the problem here?
Change new SimpleDateFormat("yyyy-MM-DD") to new SimpleDateFormat("yyyy-MM-dd").
DD is "Day in year" but you need dd "Day in month".
See http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html for Date and Time Patterns.
I have a time input in the following format from a RSS feed:
Wed Jun 13 17:05:44 +0000 2012
and I need output as Wed Jun 13, 2012 22:35:44
The source time will be always in GMT, and the required output time will be in the device time zone(it may be GMT+5:30 or GMT-2:00 or any).
So firstly I have an calendar instance with GMT, as follows.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Then modified the calendar like following using StringTokenizer on input time.
calendar.set(Calendar.DAY_OF_MONTH, date);
calendar.set(Calendar.MONTH, month);
.
.
etc.
Next I have the following code:
calendar.setTimeZone(TimeZone.getDefault());
Basically the above code changes a calendar into device time zone.
Now the matter is the above code is working fine in normal environment, but not working in Android.
Any solution? Please help.
First you required DateFormat to parse string value in Date object and then you can set Timezone in Date as well as you can make Calendar object with help of Date that calendar object will be your device timezone instance.
Below code is working at my side
String input_format = "EEE MMMMM dd HH:mm:ss Z yyyy";
String input_value="Wed Jun 13 17:05:44 +0000 2012";
Date date=null;
SimpleDateFormat sdf = new SimpleDateFormat(input_format);
try {
date = sdf.parse(input_value);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = sdf.getCalendar();
calendar.setTime(date);
if i understand it right, you just want to set the timezome
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setTimeZone("Europe/Paris");
this for example set the timezone to Paris
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
How to determine the date one day prior to a given date in Java?
If I have a Java.Util.Date object, what is the best way to get an object representing the 24 hours in the past of it?
Using Java 1.6 java.util.Calendar.add:
public static Date subtractDay(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.getTime();
}
Others suggest using Joda Time, which is currently JSR 310, and should later be included in Java itself.
The important thing to remember is that the Date class should represent any points in time whilst the Calendar class is used to manipulate those points in time. Last of all, SimpleDateFormat will represent them as Strings.
So, the best way is to use the Calendar class to calculate the new Date for you. This will ensure that any vagaries (Daylight Saving, Leap Years and the like) are accounted for.
I'm assuming that you don't really want to find '24 Hours previous' but actually do want a new Date instance representing 'this time yesterday' - either way, you can ask the Calendar instance for a Date 24Hours prior to another or 1 Day prior.
The Daylight savings is a great example. The UK 'sprang forward' on the 26th March 2009. So, 1 day prior to 3.00a.m. on the 26.Mar.2009 should yield 3.00a.m. 25.Mar.2009 but 24 Hrs prior will yield 2.00a.m.
public class DateTests extends TestCase {
private static String EXPECTED_SUMMER_TIME = "2009.Mar.29 03:00:00";
private static String EXPECTED_SUMMER_TIME_LESS_DAY = "2009.Mar.28 03:00:00";
private static String EXPECTED_SUMMER_TIME_LESS_24_HRS = "2009.Mar.28 02:00:00";
private static String EXPECTED_SUMMER_TIME_LESS_FURTHER_24_HRS = "2009.Mar.27 02:00:00";
public void testSubtractDayOr24Hours() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MMM.dd HH:mm:SS");
Calendar calendar = Calendar.getInstance();
// Create our reference date, 3.00 a.m. on the day the clocks go forward (they 'went' forward at 02.00)
calendar.clear();
calendar.set(2009, 2, 29, 3, 0);
Date summerTime = calendar.getTime(); // Sun Mar 29 03:00:00 BST 2009
String formattedSummerTime = formatter.format(summerTime);
calendar.add(Calendar.DAY_OF_MONTH, -1);
// Our reference date less 'a day'
Date summerTimeLessADay = calendar.getTime(); // Sat Mar 28 03:00:00 GMT 2009
String formattedSummerTimeLessADay = formatter.format(summerTimeLessADay);
// reset the calendar instance to the reference day
calendar.setTime(summerTime);
// Our reference date less '24 hours' (is not quite 24 hours)
calendar.add(Calendar.HOUR, -24);
Date summerTimeLess24Hrs = calendar.getTime(); // Sat Mar 28 02:00:00 GMT 2009
String formattedSummerTimeLess24Hrs = formatter.format(summerTimeLess24Hrs);
// Third date shows that taking a further 24 hours from yields expected result
calendar.add(Calendar.HOUR, -24);
Date summerTimeLessFurther24Hrs = calendar.getTime(); // Fri Mar 27 02:00:00 GMT 2009
String formattedSummerTimeLessFurther24Hrs = formatter.format(summerTimeLessFurther24Hrs);
// reset the calendar once more to the day before
calendar.setTime(summerTimeLess24Hrs);
// Take a 'day' from the Sat will yield the same result as date 03 because Daylight Saving is not a factor
calendar.add(Calendar.DAY_OF_MONTH, -1);
Date summerTimeLessFurtherDay = calendar.getTime(); // Fri Mar 27 02:00:00 GMT 2009
String formattedSummerTimeLessFurtherDay = formatter.format(summerTimeLessFurtherDay);
assert(formattedSummerTime.equals(EXPECTED_SUMMER_TIME));
assert(formattedSummerTimeLessADay.equals(EXPECTED_SUMMER_TIME_LESS_DAY));
assert(formattedSummerTimeLess24Hrs.equals(EXPECTED_SUMMER_TIME_LESS_24_HRS));
assert(formattedSummerTimeLessFurther24Hrs.equals(EXPECTED_SUMMER_TIME_LESS_FURTHER_24_HRS));
// This last test proves that taking 24 hors vs. A Day usually yields the same result
assert(formattedSummerTimeLessFurther24Hrs.equals(formattedSummerTimeLessFurtherDay));
}
}
For testing date functions, wwwdot-timeanddate-dot-com is a great resource.
subtract 1000*60*60*24 from the time and create a new date.
Date yesterday = new Date(d.getTime() - (1000*60*60*24));
int dayInMs = 1000 * 60 * 60 * 24;
Date previousDay = new Date(olddate.getTime() - dayInMs);
Personally if there are a lot of time/date calculations, I'd go with Joda-time.