Reputation: 35276
In GWT/Java how can we get the first day with the first hour, minute and seconds and the last day with last hour, last minute and last second of the current week?
And how to format the data this way:
2017-01-08T04:00:00.000Z
Upvotes: 0
Views: 595
Reputation: 1124
I think getStartingDayOfWeek() from com.google.gwt.user.datepicker.client.CalendarUtil
class will be helpful here.
After getting first day week, we can directly set hour, minutes and seconds to reset it date for start time.
For last week time, we can add some constant values.
Upvotes: 0
Reputation: 1151
So all you have to do is a simple math trick with date the code looks like (suppose that first day of week is Monday in your Locale)
Date myCurrentDate = new Date();
long timeInFirstWeek = (myCurrentDate.getTime() - 345600000 + 3600000) % 604800000;
Date firstDateOfWeek = new Date(myCurrentDate.getTime() - timeInFirstWeek - 3600000);
Date lastDateOfWeek = new Date(firstDateOfWeek.getTime() + 604800000 - 1);
GWT.log(DateTimeFormat.getFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(lastDateOfWeek));
GWT.log(DateTimeFormat.getFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(firstDateOfWeek));
Explanation: To find out what day of week we have right now we need some constant. In Date Time only one constant is 0 (setTime(0)) But this is a 1 January 1970 Thursday 01:00. So let's get back in time to 70'. In order to do that we divide "our time now" by time of "one week", which is 604800000 miliseconds. Because we use modulo we expect to be, in first week of 1970 year. But there is a still problem with Thursday and 01:00 hour. How to resolve this? We substract from our current time four days = 345600000 milliseconds and add this one hour 3600000. Now we landing in in Monday 00:00 1970! Now we have in variable timeInFirstWeek which indicate time which passed only in one first week of 1970. I other words we remove all other weeks from time and we have only one week.
So now you are probably guessing that all we have to do is to substract timeInFirstWeek from current date to get first second of the week. In order to get last second of week we need to add one week = 604800000 and then substract one millisecond.
With formatting as @Knarf mentioned you may use DateTimeFormat. Additionally it has been removed temporary from deprecation in GWT 2.8 as code says
// Temporarily remove deprecation to keep from breaking teams that don't allow
// deprecated references.
// @Deprecated
Upvotes: 1