How to get the right week of year number through a Calendar? - java

guys,i am confused by invoking the following method:Calendar.getInstance().get(Calendar.WEEK_OF_YEAR),the result got from that method is not right.Here is my Code:
Locale.setDefault(Locale.CHINA);
Calendar calendar = Calendar.getInstance();
//we think Monday is the first day of a week in China,but not Sunday.
calendar.setFirstDayOfWeek(Calendar.MONDAY);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = "2010-01-01";
calendar.setTime(sdf.parse(dateString));
System.out.println("DateString: " + dateString + ", week: " + calendar.get(Calendar.WEEK_OF_YEAR));
dateString = "2010-12-27";
calendar.setTime(sdf.parse(dateString));
System.out.println("DateString: " + dateString + ", week: " + calendar.get(Calendar.WEEK_OF_YEAR));
The result is
DateString: 2010-01-01, week: 1//This may be wrong?
DateString: 2010-12-27, week: 1//This result is definitely wrong.
So here is the question, how to get the right week of year number using Calendar instance?

The locale has only influence on formatting (i.e., parsing and formatting the date as Chinese). You need to set the timezone to China. Fix the Calendar#getInstance() line as follows:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("CST")); // China Standard Time

Try this:
Calendar calendar = Calendar.getInstance();
calendar.setMinimalDaysInFirstWeek(4);

Related

Given a calendar.week_of_year, How do I get the dates for the start and end of the week?

Given a week_of_year, how can I get the dates for the start and end of the week?
Example:
Let's say the date is Jan/1/2017.
Calendar calendar = Calendar.getInstance();
// Let's assume that we've set calendar to Jan/1/2017.
Integer week_of_year = calendar.get(Calendar.WEEK_OF_YEAR)
week_of_year would return 1. Presumably, week 1 is anything between Jan/1/2017 to Jan/7/2017.
How can I reverse lookup week_of_year=1 and get the min/max of Jan/7/2017 to Jan/6/2017? or for any other valid week_of_year value.
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, 1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Start Date: " + sdf.format(cal.getTime()));
cal.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("End Date: " + sdf.format(cal.getTime()));

Why does SimpleDateFormat show unix date as December 31 1969?

I am working on a date picker where there is a range of dates. I noticed that all of my dates are a day behind and while investigating the issue I narrowed down the problem to the SimpleDateFormat object. No matter what Unix time I give it it sets the date to the previous day. An example of this behaviour is
String myFormat = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat);
Log.d(TAG, "Time Zone: " + cal.getTimeZone().getDisplayName());
Log.d(TAG, "Printable: " + sdf.format(0));
The output that I see in the logger is
Time Zone: UTC
Printable: 12/31/1969
Why does the formatter use December 31 instead of January 1st 1970?
Because the DateFormat also has a TimeZone (and your system isn't set to UTC). You can change it with DateFormat.setTimeZone(TimeZone). Something like
String myFormat = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("Printable: " + sdf.format(0));
Output is (as you expected)
Printable: 01/01/1970

Getting UTC time with Calendar and Date [duplicate]

This question already has answers here:
Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time
(7 answers)
Closed 8 years ago.
I'm trying to get an instance of Date with UTC time using the following code:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Date now = cal.getTime();
that looks so simple, but if I check the values at IntelliJ's debugger, I get different dates for cal and now:
cal:java.util.GregorianCalendar[time=1405690214219,areFieldsSet=true,lenient=true,zone=GMT,firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=6,WEEK_OF_YEAR=29,WEEK_OF_MONTH=3,DAY_OF_MONTH=18,DAY_OF_YEAR=199,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=1,HOUR_OF_DAY=13,MINUTE=30,SECOND=14,MILLISECOND=219,ZONE_OFFSET=0,DST_OFFSET=0]
now:Fri Jul 18 10:30:14 BRT 2014
as you can see, cal is 3 hours ahead of now... what am I doing wrong?
Thanks in advance.
[EDIT] Looks like TimeZone.setDefault(TimeZone.getTimeZone("UTC")); before the code above does the job...
This question has already been answered here
The System.out.println(cal_Two.getTime()) invocation returns a Date from getTime(). It is the Date which is getting converted to a string for println, and that conversion will use the default IST timezone in your case.
You'll need to explicitly use DateFormat.setTimeZone() to print the Date in the desired timezone.
TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US);
simpleDateFormat.setTimeZone(timeZone);
System.out.println("Time zone: " + timeZone.getID());
System.out.println("default time zone: " + TimeZone.getDefault().getID());
System.out.println();
System.out.println("UTC: " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Default: " + calendar.getTime());
Edit To convert cal to date
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DATE);
System.out.println(year);
Date date = new Date(year - 1900, month, day); // is same as date = new Date();
Just build the Date object using the Cal values. Please let me know if that helps.
Try using a date formatter and set the time zone to UTC.
dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));

Time Zones in Java

I'm working on a security signature in java that also verifies the date and time the call is being made. The POST call arrives with something like
String date = "Sat, 27 Apr 2013 01:11:30 GMT"
SimpleDateFormat RFC1123Format = new SimpleDateFormat("EEE, dd MMM yyyyy HH:mm:ss z", Locale.US);
And I'm able to parse it
Calendar gmtTime = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
Date dateHeader = RFC1123Format.parse(date);
gmtTime.setTime(dateHeader);
System.out.println("Date Header (GMT TIME): " + gmtTime.getTimeInMillis() + " ms");
System.out.println("Hour of day (GMT TIME): " + gmtTime.get(Calendar.HOUR_OF_DAY));
Calendar currentTime = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
currentTime.setTimeInMillis(System.currentTimeMillis());
System.out.println("System Date (LA TIME): " + currentTime.getTimeInMillis() + " ms");
System.out.println("Hour of day (LA TIME): " + currentTime.get(Calendar.HOUR_OF_DAY));
currentTime.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("System Date (GMT TIME): " + currentTime.getTimeInMillis() + " ms");
System.out.println("Hour of day (GMT TIME): " + currentTime.get(Calendar.HOUR_OF_DAY));
System.out.println("Diff: " + Math.abs(gmtTime.getTimeInMillis() - currentTime.getTimeInMillis()));
However the printout I get differs by 1 entire hour.
Date Header (GMT TIME): 1367025090000 ms
Hour of day (GMT TIME): 1
System Date (LA TIME): 1367022298441 ms
Hour of day (LA TIME): 0
System Date (GMT TIME): 1367022298441 ms
Hour of day (GMT TIME): 0
Diff: 2791559
Any ideas?
You can use JodaTime >> http://joda-time.sourceforge.net/ that implements TimeZone Calculations more efficiently than Java calendar
You don't give your formatter the calendar that you are using to represent your timestamps.
In this case, your calendar is set to represent timestamps in GMT. GMT is a synonym for UTC and UTC never observes any adjustment for DST. Your formatter, however, by default must convert your supplied string with the system default calendar as the basis, which likely does observe DST.
If this is the case, you can get consistent reporting by making sure that your formatter is using the same calendar that you are using to represent your date/times. Try this:
SimpleDateFormat RFC1123Format = new SimpleDateFormat();
GregorianCalendar gc - new GregorianCalendar(TimeZone.getTimeZone("GMT"));
RFC1123Format.setCalendar(gc);
RFC1123Format.applyPattern("EEE, dd MMM yyyyy HH:mm:ss z");
gc.setTime(RFC1123Format.parse(yourDateString));
Fixed it myself by adding an extra verification to check if Daylight Savings is being observed. This is the final code:
Calendar gmtTime = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
Date dateHeader = RFC1123Format.parse(date);
gmtTime.setTime(dateHeader);
Calendar currentTime = Calendar.getInstance();
currentTime.setTimeInMillis(System.currentTimeMillis());
boolean DST = false;
if(currentTime.getTimeZone().inDaylightTime(currentTime.getTime())) {
DST = true;
}
currentTime.setTimeZone(TimeZone.getTimeZone("GMT"));
if(DST) {
currentTime.set(Calendar.HOUR_OF_DAY, currentTime.get(Calendar.HOUR_OF_DAY) + 1);
.
.
.
<code to handle last day of month and month change as a result of the hour adjustment>
}
Thanks #gangqinlaohu for your suggestion.

How to retrieve the current day of the week?

How would I get the current day of the week?
Can some please help me?
Use a Calendar and get the DAY_OF_WEEK field:
Calendar cal = Calendar.getInstance();
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
Or if you want the day name instead, you can use SimpleDateFormat:
Date today = Calendar.getInstance().getTime();
DateFormat df = new SimpleDateFormat("EEEE", Locale.ENGLISH); // override the default Locale
String dayNameInWeek = df.format(today);
To get a text display of the day of the week you can use:
DateFormat dateFormat = new SimpleDateFormat("EEEE");
System.out.println("Today is " + dateFormat.format(new Date()));
output:
Today is Sunday

Categories

Resources