I have the following code :-
Calendar calc = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MMM-yyyy");
calc.set(Calendar.YEAR, calc.get(Calendar.YEAR) - 1);
calc.set(Calendar.MONTH, Calendar.NOVEMBER);
System.out.println("---NOV? : " + sdf.format(calc.getTime()));
Calendar calc1 = Calendar.getInstance();
calc1.set(Calendar.YEAR, calc1.get(Calendar.YEAR) - 1);
calc1.set(Calendar.MONTH, Calendar.DECEMBER);
System.out.println("-- DEC : " + sdf.format(calc1.getTime()));
The output of the above code is :-
> ---NOV? : Dec-2012
> -- DEC : Dec-2012
This happens only for 31st january, can someone explain why this might be happening?
The Calendar is set for lenient interpretation, so if you tell it the 31st day of November, well, November only has 30 days, so it rolls over to December 1st.
I suspect the first case is rounding "November 31" to "December 1", since you're not changing the day in your calendar.
Related
int year = Integer.parseInt(sTransDateTime2.substring(0, 4));
int month = (Integer.parseInt(sTransDateTime2.substring(4, 6)) - 1);
int day = Integer.parseInt(sTransDateTime2.substring(6, 8));
int hour = Integer.parseInt(sTransDateTime2.substring(8, 10));
int minute = Integer.parseInt(sTransDateTime2.substring(10, 12));
int second = Integer.parseInt(sTransDateTime2.substring(12));
System.out.println("year=" + year + "| month= " + month + "| day=" + day);
DateFormat df = new SimpleDateFormat("mm/dd/yyyy");
Calendar calConvert = Calendar.getInstance();
calConvert.set(year, month, day, hour, minute, second);
sTransDateTime2 = Long.toString(calConvert.getTimeInMillis() / 1000);
System.out.println("debug date: " + sTransDateTime2);
my date time is year=2017| month= 7| day=28| hour= 17| minute=0,
After convert to milliseconds it become 1501232400.
The result of date is correct, will be 28 Jul 2017, but time become 9.00pm.
Any wrong on my coding?
Thanks
stop learning the old broken java.date and move into the java.time
LocalDateTime myldt = LocalDateTime.of(2017, 7, 28, 17, 0);
System.out.println(myldt);
System.out.println(myldt.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
It looks like the conversion to milliseconds is being done in one TimeZone, but the system on which the milliseconds are converted to date is in a different timezone.
28th July, 2017 17:00:00 gives seconds from epoch as 1501232400 when in UTC+08:00 timezone, but these seconds from epoch give back 28th July, 2017 21:00:00 in UTC+12:00 timezone.
To illustrate the above, I have explicitly set the timezone to UTC+8:00 when calculating the milliseconds. (I have set my system timezone to UTC+12:00 to show the output)
System.out.println("year=" + year + "| month= " + month + "| day=" + day);
Calendar calConvert = Calendar.getInstance();
calConvert.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
calConvert.set(year, month, day, hour, minute, second);
sTransDateTime2 = Long.toString(calConvert.getTimeInMillis() / 1000);
System.out.println("debug date: " + sTransDateTime2);
System.out.println(new Date(calConvert.getTimeInMillis()));
This gives me the output as below:
year=2017| month= 6| day=28
debug date: 1501232400
Fri Jul 28 21:00:00 NZST 2017
Please note that Date always prints the date in local timezone. So, it has converted the milliseconds as per local timezone and the time changes to 21:00.
Now I format this date to make sure that I get the output back in UTC+08:00 only, whatever be the system timezone.
Date dt = calConvert.getTime();
DateFormat formatter= new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
System.out.println(formatter.format(dt));
Now I get the output as : 07/28/2017 17:00:00 instead of the earlier date with 21:00 as time.
So, the conclusion is that you need to format the date to be displayed in a specific timezone, if you want to avoid it picking up the default timezone of the system on which it is displayed.
To avoid all the cumbersome code and confusing issues, as suggested in the other answer, go for the java.time API. java.time is available from JDK 8. As you are using JDK 6, you can use the ThreeTen Backport. Just to illustrate the ease with which things could be done with java.time , the following does the same what your code does , but in a concise and easily understandable way:
ZonedDateTime zdt = ZonedDateTime.of(LocalDate.of(year, month, day),
LocalTime.of(hour, minute,second), ZoneId.of("Asia/Macau"));
long secondsFromEpoch = zdt.toEpochSecond();
//To convert back
ZonedDateTime zdtBack = Instant.ofEpochSecond(secondsFromEpoch)
.atZone(ZoneId.of("Asia/Macau"));
System.out.println(zdtBack);
How to get week of particular selected date?
For Example:
My week will start from Monday and ends on Sunday.
So lets say i have selected 25 July 2017. So i want what was the date on monday of that week and what is the date on upcoming Sunday of that week.
The answer should be :: Monday -- 24 July 2017 AND Sunday-- 30 July 2017.
I am not able to find a simple way to get it.
You can see this. It is for the present date.
Calendar cal = Calendar.getInstance();
int week = cal.get(Calendar.WEEK_OF_MONTH);
int day = cal.get(Calendar.DAY_OF_WEEK);
System.out.println(day);
Date mondayDate = null;
if (day > 2) {
int monday = day - 2;
cal.add(Calendar.DATE, -monday);
mondayDate = cal.getTime();
} else {
// cal.add(Calendar.DATE,);
mondayDate = cal.getTime();
}
int sunday = 7 - day + 1;
cal.add(Calendar.DATE, +sunday);
Date sundaydate = cal.getTime();
System.out.println(mondayDate);
System.out.println(sundaydate);
}
In this, we are finding the day of the week.Today we will get
day=2.
Now for monday,we will first check days.
if day=1, means it is sunday.
if day=2, means it is monday.
so for day>2, we are getting date of (day-2) days back. For today, day=1. hence mondaydate= 23 July,2017.
Similarily for sunday, we are getting date of (7-day+1) days later. For today, sunday=5, so after +6, sundaydate= 31 july,2017
Hope this helps :)
You can get like this :
String date = (String) android.text.format.DateFormat.format("dd", date);
String dayOfTheWeek = (String) DateFormat.format("EEEE", date);
For next Sunday you can calculate as per dayOfTheWeek.
If the input is today(June 7), then it should give me May 1 12:00 AM to May 31, 11:59 PM.
I was using Calendar but I want to use DateUtils.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, -1);
calendar.set(Calendar.HOUR,23);
calendar.set(Calendar.MINUTE,59);
calendar.set(Calendar.SECOND,59);
System.out.println("Last date of month: " + calendar.getTime());
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR, 12);
calendar.set(Calendar.MINUTE,00);
calendar.set(Calendar.SECOND,00);
System.out.println("fir stdate of month: " + calendar.getTime());
DateUtils can do the required:
Date lastmonth = DateUtils.addMonths(new Date(), -1);
System.out.println(lastmonth);
System.out.println(DateUtils.truncate(lastmonth, Calendar.MONTH));
System.out.println(DateUtils.addMinutes(DateUtils.ceiling(lastmonth, Calendar.MONTH), -1));
Edit: Adding output
Sat May 07 23:06:05 AST 2016
Sun May 01 00:00:00 AST 2016
Tue May 31 23:59:00 AST 2016
I ended up using JodaTime. Much easier!
MutableDateTime dateTime = new MutableDateTime();
System.out.println("CurrentTime " + dateTime);
dateTime.addMonths(-1); //last Month
dateTime.setMinuteOfDay(0);
dateTime.setSecondOfMinute(0);
dateTime.setHourOfDay(12);
dateTime.setDayOfMonth(1); //first Day of last Month
System.out.println("first Day Time " + dateTime);
dateTime.setDayOfMonth(dateTime.dayOfMonth().getMaximumValue()); //set Day to last Day of that month
dateTime.setMinuteOfDay(59);
dateTime.setSecondOfMinute(59);
dateTime.setHourOfDay(23); //time set to night time 11:59:59
System.out.println("last Day Time " + dateTime);
I'm looking to utilize GregorianCalendar to do some logic based on days. Is there any way to see if 2 dates are in the same week? I've tried using get(Calendar.WEEK_OF_YEAR), and this has the two downsides of:
1) Starting on the wrong day of the week (which seems to have a potential solution in setFirstDayOfWeek, however preliminary testing has not been successful.
2) This solution does not carry over years nicely. For example - Dec 30th, 2014 and Jan 1, 2015 should be in the same week.
Is there any solution to this that doesn't require switching libraries?
OK, since you've stated there will be a time component, I'd use something similar to #MadProgrammer's answer, but without the complexity of using an entire date range. I'd have a static method something like this.
public static Date firstOfWeek(Calendar cal) {
Calendar copy = new GregorianCalendar(
cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
copy.set(Calendar.DAY_OF_WEEK, copy.getFirstDayOfWeek());
return copy.getTime();
}
This returns a Date for the first day of the week that includes a particular Calendar. You can then check whether two calendars fall in the same week like this.
if (firstOfWeek(cal1).equals(firstOfWeek(cal2))) {
...
}
You question basically boils down to determining if a given date falls within a given date range (ie a week).
The idea behind this is basically one of the two date's acts as the anchor, from which we calculate the date range (start of week to end of week) and then determine if the other date falls within that range.
So, first, we need to calculate the date range, something like...
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
Date startOfWeek = cal.getTime();
cal.add(Calendar.DATE, 6);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);
Date endOfWeek = cal.getTime();
Which will give us two dates, the first starting at the "start of the week" and one 6 days later (the "end of the week"). We force the time values to the extreme of the days to ensure we can capture the fall range
Next, we need to determine if the other date is equal to or after the "start of the week" and equal to or before the "end of the week", something like...
(date2.equals(startOfWeek) || date2.after(startOfWeek)) && (date2.equals(endOfWeek) || date2.before(endOfWeek));
This could then be wrapped up in a nice little method to make calling it simpler...
public static boolean isInSameWeek(Date date1, Date date2) {
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
Date startOfWeek = cal.getTime();
cal.add(Calendar.DATE, 6);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);
Date endOfWeek = cal.getTime();
System.out.println("Week starts at : " + startOfWeek);
System.out.println(" Week ends at : " + endOfWeek);
return (date2.equals(startOfWeek) || date2.after(startOfWeek)) && (date2.equals(endOfWeek) || date2.before(endOfWeek));
}
And then we can test it...
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
Date date1 = sdf.parse("30/12/2014");
Date date2 = sdf.parse("1/1/2015");
System.out.println("Is in same week " + date1 + "/" + date2 + " = " + isInSameWeek(date1, date2));
System.out.println("");
date1 = sdf.parse("27/12/2014");
System.out.println("Is in same week " + date1 + "/" + date2 + " = " + isInSameWeek(date1, date2));
} catch (ParseException exp) {
exp.printStackTrace();
}
Which outputs something like...
Week starts at : Sun Dec 28 00:00:00 EST 2014
Week ends at : Sat Jan 03 23:59:59 EST 2015
Is in same week Tue Dec 30 00:00:00 EST 2014/Thu Jan 01 00:00:00 EST 2015 = true
Week starts at : Sun Dec 21 00:00:00 EST 2014
Week ends at : Sat Dec 27 23:59:59 EST 2014
Is in same week Sat Dec 27 00:00:00 EST 2014/Thu Jan 01 00:00:00 EST 2015 = false
//this month
SimpleDateFormat df_formonth = new SimpleDateFormat("MMM");
c.set(Calendar.MONTH, 5); //integer to be changed upon click - maybe month counter from now
String currmonth = df_formonth.format(c.getTime());
This should return June since we index months from 0 to 11
but it returns july
any solutions or other ways to fix this?
Because today's date is the 31st of August and June only has 30 days, the month is automatically incremented to the following month giving July.
To solve you can set the date before setting the month
c.set(Calendar.DATE, 30);
c.set(Calendar.MONTH, Calendar.JUNE);
Also I suggest using Calendar constants for clarity
Well known issue when you are working with dates at the end of the month (31st of Aug).
You should explicitly set the date.
For example read here for details:
http://www.coderanch.com/t/385083/java/java/java-util-Calendar-set
You can try the following:
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int day = cal.get(Calendar.DAY_OF_MONTH);
cal.clear();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.DAY_OF_MONTH, day);
cal.set(Calendar.MONTH, Calendar.JUNE);