How to calculate next week? - java

I want to precisely calculate the time one week from a given date, but the output I get back is one hour early.
code:
long DURATION = 7 * 24 * 60 * 60 * 1000;
System.out.println(" now: " + new Date(System.currentTimeMillis()));
System.out.println("next week: " + new Date(System.currentTimeMillis() + DURATION));
output:
now: Wed Sep 16 09:52:36 IRDT 2015
next week: Wed Sep 23 08:52:36 IRST 2015
How can I calculate this correctly?

Never, ever rely on millisecond arithmetic, there are too many rules and gotchas to make it of any worth (even over a small span of time), instead use a dedicated library, like Java 8's Time API, JodaTime or even Calendar
Java 8
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = now.plusDays(7);
System.out.println(now);
System.out.println(then);
Which outputs
2015-09-16T15:34:14.771
2015-09-23T15:34:14.771
JodaTime
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = now.plusDays(7);
System.out.println(now);
System.out.println(then);
Which outputs
2015-09-16T15:35:19.954
2015-09-23T15:35:19.954
Calendar
When you can't use Java 8 or JodaTime
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DATE, 7);
Date then = cal.getTime();
System.out.println(now);
System.out.println(then);
Which outputs
Wed Sep 16 15:36:39 EST 2015
Wed Sep 23 15:36:39 EST 2015
nb: The "problem" you seem to be having, isn't a problem at all, but simply the fact that over the period, your time zone seems to have entered/exited day light savings, so Date is displaying the time, with it's correct offset

Try this
Calendar cal = Calendar.getInstance();
System.out.println(cal.getTime());
cal.add(Calendar.DAY_OF_MONTH, 7);
System.out.println(cal.getTime());

The difference is because of the different timezone. IRDT is +0430 and IRST is +0330
To overcome this issue you can use the JodaTime.
LocalDateTime now = LocalDateTime.now();
LocalDateTime nextweek = now.plusDays(7);
System.out.println(now);
System.out.println(nextweek);

As other said. It would be better to use Calendar or JodaTime library. But the question is why you were not getting the desired result. It was because currentTimeMillis() calculates time between "computer time" and coordinated universal time (UTC). Now consider following case.
long DURATION = 7 * 24 * 60 * 60 * 1000;
Date now = new Date();
Date nextWeek = new Date(now.getTime() + DURATION);
System.out.println(" now: " + now);
System.out.println("next week: " + nextWeek);
here Date.getTime() calculate time from 00:00:00 GMT every time and then when converted to string will give time for your local time zone.
Edit :
I was wrong. The reason is as simon said.
The actual "why" is that IRDT (Iran Daylight Time) ends on September
22nd. That's why the first date (September 16th) in the OP's post is
displayed as IRDT and the second date (September 23rd) is displayed as
IRST. Because IRST (Iran Standard Time) is one hour earlier than IRDT
the time displayed is 08:52:36 instead of 09:52:36.

Related

How to get selected month last date last timestamp in java?

From the below java code I'm getting a month First & last dateTimestamp, but here i need last dateTimestamp as - "Mon Aug 31 23:59:59 IST 2015" instead of - "Mon Aug 31 00:00:00 IST 2015"?
Calendar cal = Calendar.getInstance();
int year = 2015;
int month = 07;
cal.set(cal.DATE,1);
cal.set(cal.YEAR,year);
cal.set(cal.MONTH, month);
String firstDate = (cal.getActualMinimum(cal.DATE) + "/" + (month+1) + "/" +year);
System.out.println("firstDate-->"+"\t"+firstDate);
String lastDate = (cal.getActualMaximum(cal.DATE) + "/" + (month+1) + "/" +year);
System.out.println("lastDate-->"+"\t"+lastDate);
DateFormat firstFormat = new SimpleDateFormat("dd/MM/yyyy");
Date beginDate = firstFormat.parse(firstDate);
System.out.println("BeginDate Timestamp"+ "\t" + beginDate);
DateFormat secoundFormat = new SimpleDateFormat("dd/MM/yyyy");
Date endDate = secoundFormat.parse(lastDate);
System.out.println("endDate Timestamp"+ "\t" + endDate);
Output:->
firstDate--> 1/8/2015
lastDate--> 31/8/2015
BeginDate Timestamp Sat Aug 01 00:00:00 IST 2015
endDate Timestamp Mon Aug 31 00:00:00 IST 2015
Please help me if we have any solution.
If I understand your question, it looks as if you want to pass a year and month into a method, and get back the last day of the passed month.
I would suggest consider (in this order):
which jdk you use
configuration of calendar
configuration of timezone (maybe)
using jodatime
As of 1.8 many JodaTime-like features have been added to the jdk- e.g. see https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html (If you arent using 1.8 you can use the joda lib, assuming your organization allows it)
Calendar.getInstance() gives a default TimeZone and a default Locale, which means the definitions of the running JVM. You may or may not need to consider this and implement more than just getInstance(). See API javadoc.
Assuming a Gregeorian Calendar (hey, you could be Bahaian and have 19 months in the year ...) , here is one partial implementation using JDK 1.7, JodaTime jar 2.2, validation-1.0.0.GA jar:
#Test
public void testDate() {
final String dateStringOfFirstDay = "1.7.2015";
final Date lastDayOfMonth = getLastDayOfMonth(dateStringOfFirstDay);
Assert.assertNotNull(lastDayOfMonth);
//more assertions ...
}
private Date getLastDayOfMonth(#NotNull String dateStringOfFirstDay) {
//further validation here necessary according to required date format
DateTime dt = DateTime.parse(dateStringOfFirstDay);
return dt.dayOfMonth().withMaximumValue().toDate();
}
The defintion of DateFormat/DateTimeFormat and further result assertions is left up to you.
Best of luck!
Guys I got a solution for my question!!!
I think it will help u too...
Calendar calendar = Calendar.getInstance();
int year=2015;
int month=7;
int date=31;
int hourOfDay=23;
int minute=59;
int second=59;
int milliSecond=999;
calendar.set(year, month, date, hourOfDay, minute, second);
calendar.set(calendar.MILLISECOND, milliSecond);
System.out.println("Time from Calendar: "+calendar.getTime());
long timeInMilliSeconds=calendar.getTimeInMillis();
System.out.println("timeInMilliSeconds from calendar: "+timeInMilliSeconds);
Timestamp timestamp=new Timestamp(timeInMilliSeconds);
System.out.println(timestamp);
The above program gives the last date last timestamp in a selected month.
getTimeInMillis() takes the time from Jan 01, 1970 to current time in Milliseconds.
Using those milliseconds i'm getting the Timestamp.
Thank you for your help guys!!!
OutPut:->
Time from Calendar: Mon Aug 31 23:59:59 IST 2015
timeInMilliSeconds from calendar: 1441045799999
2015-08-31 23:59:59.999

Java date string parse creates difference of timezone

I am bit frustrated by this.
I have a String "2015-02-18T23:44:59" which represents time in GMT format.
I want to parse this date into date object.
String dateStr = "2015-02-18T23:44:59";
Date date = DateUtils.parseDate(dateStr, new String[]{"yyyy-MM-dd'T'HH:mm:ss"});
System.out.println(dateStr + " \t" + date.toString());
This outputs :
2015-02-18T23:44:59 Thu Feb 19 05:14:59 IST 2015
As you can see latter time has time zone IST but my original time was GMT.
I don't think there is any parse function which takes current date's time zone.
One way to answer is this question is that :
date.setTime(date.getTime() + ( date.getTimezoneOffset() * 60 * 1000));
System.out.println("\t" + date.toString());
This outputs:
Wed Feb 18 23:44:59 IST 2015
Which seems correct time (but incorrect time zone). Additionally, getTimezoneOffset() is deprecated.
Can anyone suggest me a better way to deal with String dates considering time zones.
I'd use a date format:
SimpleDateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = utcFormat.parse("2015-02-18T23:44:59");

Timestamp to Date issue

I'm trying to create a function that convert a timestamp to Date object.
My problem is that using this online tools i reach correctly to convert timestamp to date but using java it doesn't convert correctly.
This is what i try:
public static Date getDateFromUUID(UUID uuid) {
Calendar uuidEpoch = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
uuidEpoch.clear();
uuidEpoch.set(1582, 9, 15, 0, 0, 0);
long epochMillis = uuidEpoch.getTime().getTime();
long time = (uuid.timestamp() / 10000L) + epochMillis;
Calendar start = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Calendar end = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
start.setTimeInMillis(time*1000);
end.set(start.get(Calendar.YEAR), start.get(Calendar.MONTH), start.get(Calendar.DAY_OF_MONTH),0,0,0);
return end.getTime();
}
I'm trying using that uuid: a261ae00-2a9c-11b2-ae56-bcee7be23398
it correctly converts to timestamp : 1406412000
Using this:
Calendar start = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Calendar end = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
start.setTimeInMillis(time*1000);
end.set(start.get(Calendar.YEAR), start.get(Calendar.MONTH), start.get(Calendar.DAY_OF_MONTH),0,0,0);
return end.getTime();
I need to remove hours, minutes and seconds and take only years,months and days.
but it convert timestamp to
Sat Jul 26 02:00:00 CEST 2014
Instead of
Sun Jul 27 00:00:00 CEST 2014
what could be my mistake?
Thanks!
Your time zone if wrong. Notice that output is CEST but you set the calendar to UTC. The delta between these two is 2 hours. When you output the Date you need to set the timezone appropriately.

Subtracting two dates in Java

I want to subtract two dates (one constant and one current) in Java but I've got strange problems with it. Here is the code :
DateFormat df = new SimpleDateFormat("HH:MM");
Date FirstLessonInterval=df.parse("08:45");
Date currentTime = new Date();
long diff = FirstLessonInterval.getTime()-currentTime.getTime();
String s = String.valueOf(diff);
LessonOrBreak=(diff);
I've got minus minutes. When I want to see FirstLessonInterval with FirstLessonInterval.toString() it shows the year 1970. What can I do?
You forgot to give a date, you just defined a time:
DateFormat df = new SimpleDateFormat("HH:MM");
Date FirstLessonInterval=df.parse("08:45");
and this is in unix time day 0 which is the 1.1.1970
try something like
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:MM");
Date FirstLessonInterval=df.parse("2014/05/10 08:45");
1970 is where all time began according to computers. Are we missing some code in your question? You can faff around with the current time in milliseconds but i'd take a look at JodaTime and use that.
The reason you are getting 1970.... is because I suspect your diff is quite a small number. Then if you look at that as a date then it will be a small number + 1 Jan 1970 which will still be in 1970. But as i said I suspect we are missing some code in your question.
In JodaTime you can do somethign like the below but im not sure what it is you are exactly after
Interval i= new Interval(new DateTime(FirstLessonInterval), new DateTime());
System.out.println("Interval is: " + i.toDurationMillis());
Your format pattern is incorrect, use lower case mm to represent minutes
When you do not specify much details to the outdated Java date api, it considers the time since UNIX epoch (1st Jan 1970)
Since you are assuming the date to be the same as the constant time parameters you provide and independent of the timezones, you can bring your current date comparable to the time since UNIX epoch:
Staying close to your original code;
DateFormat df = new SimpleDateFormat("HH:mm");
Date firstLessonInterval = df.parse("08:45");
Date currentTime = new Date();
// Format the current date comparable to UNIX epoch (only hold time params)
String dateStr = df.format(currentTime.getTime());
// Parse the modified date string to a date object
Date comDate = df.parse(dateStr);
// Take the difference in millis
long diff = firstLessonInterval.getTime() - comDate.getTime();
String s = String.valueOf(diff);
// Print the number of minutes passed since
System.out.println("Minutes {elapsed since/time to} 08:45 - " + Math.abs(diff) / 1000 / 60);
Missing Date Portion
As the other correct answers said, you are using the java.util.Date class which is a date-time class holding both a date portion and a time portion.
LocalTime
If you truly care about only time of day, with no date and no time zone, then use the LocalTime class found in both the Joda-Time library and the new java.tome package in Java 8. By the way the old java.util.Date and .Calendar classes are notoriously troublesome and should be avoided.
Joda-Time
Here is some code with date-time and time zone.
Using the Joda-Time 2.3 library…
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Warsaw" );
DateTime dateTime = new DateTime( 2014, 1, 2, 8, 45, 0, timeZone );
DateTime now = new DateTime( 2014, 1, 2, 8, 30, 0, timeZone ); // Or DateTime.now( timeZone )
Duration duration = new Duration( dateTime, now ); // or use Period or Interval.
Joda-Time offers intelligent classes and methods of working with a span of time (a Period, Interval, or Duration). For example look at the Minutes class. But if all you need is millseconds, here you go.
long millis = duration.getMillis();
The problem is that you are not providing enough info to SimpleDateFormat. It sets the hour and minutes correctly but nothing else.
DateFormat df = new SimpleDateFormat("HH:mm");
System.out.println(df.parse("08:45")); // Thu Jan 01 08:45:00 GMT 1970
System.out.println(new Date()); // Sun May 11 07:52:50 GMT 2014
If you want your date to be with respect to the current date try this:
Date curr = new Date();
Date date = new Date(curr.getYear(),
curr.getMonth(),
curr.getDate(),
8, 45, 0);
System.out.println(date); // Sun May 11 08:45:00 GMT 2014
System.out.println(curr); // Sun May 11 07:52:50 GMT 2014
long diff = date.getTime() - curr.getTime();
System.out.println("Minutes: " + diff/6000); // Minutes: 53
I dont know if this way is efficient or not but it's an idea anyway:
Date curr = new Date();
Date date = new Date(114, /*114 is 2014 , don't know why*/
6,
16,
8, 45, 0);
System.out.println(curr);
System.out.println(date);
Date x = new Date(curr.getYear() - date.getYear() ,
curr.getMonth() - date.getMonth(),
curr.getDate() - date.getDate(),
curr.getHours() - date.getHours(),
curr.getMinutes() - date.getMinutes(),
curr.getSeconds() - date.getSeconds() );
String startDateString = "2017-03-08";
String finishDateString = "2017-03-10";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
LocalDate startDate = LocalDate.parse(startDateString, formatter);
LocalDate finishDate = LocalDate.parse(finishDateString, formatter);
Integer day = finishDate.compareTo(startDate);
Integer day will be 3. It means that the difference between two dates equals 3 days

Get Previous Day [duplicate]

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.

Categories