Java calendar problem, JDK 1.6.0.22 - windows

I have a problem with getting the week of year. On my machine JDK 1.6.0.22 version is installed, on another machine 1.6.0.21. And both machines return different results:
(1.6.0.22) week is: 1 (1.6.0.21) week is: 52
For this code:
try {
Calendar current = new GregorianCalendar();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date d = df.parse("2010-12-28 19:04:38 GMT");
current.setTime(d);
int currentWeek = current.get(Calendar.WEEK_OF_YEAR);
System.out.println("week is: "currentWeek);
} catch (ParseException e) {
e.printStackTrace();
}
Why does JDK 1.6.0.22 give the wrong result?

This excerpt from the API documentation explains why this difference can occur:
Values calculated for the WEEK_OF_YEAR
field range from 1 to 53. Week 1 for a
year is the earliest seven day period
starting on getFirstDayOfWeek() that
contains at least
getMinimalDaysInFirstWeek() days from
that year. It thus depends on the
values of getMinimalDaysInFirstWeek(),
getFirstDayOfWeek(), and the day of
the week of January 1.
And from the source code of Calendar:
Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent.
So it's the locale that determines this, not the time zone! Apparently, in some locales, week 1 of a year is considered to begin in the previous year. Try running this:
Calendar cal = new GregorianCalendar();
System.out.println(Locale.getDefault());
System.out.println(cal.getMinimalDaysInFirstWeek());
System.out.println(cal.getFirstDayOfWeek());
I bet that either you're running the different versions in different locales, or the locale data changed between these versions. The result "1" could even be the more correct one and due to a bug fix in the locale data.

Don't use the JDK date/time classes - use JODA Time instead.

Related

Is there a way to make __timeShift only select certain days of the week?

The current function in use in the JMeter script is
${__timeShift(dd/MM/yyyy,${__time(dd/MM/yyyy)},-P31D,,)}
to specify a review date 31 days ago.
I now learn that the project requires the review date to always fall on a Monday. Is there any way to make sure that performing a timeShift only selects a Monday?
I'm afraid __timeShift() function is not flexible enough, you can consider using __groovy() function instead and implement the following algorithm:
Get current date
Subtract 31 day
If current day of week is Monday - return the date in the past
Otherwise add 1 day until the date in the past becomes Monday
Example function code:
${__groovy(def now = new Date(); def monthAgo = now.minus(31); while (monthAgo[Calendar.DAY_OF_WEEK] != Calendar.MONDAY) { monthAgo = monthAgo.plus(1)}; return monthAgo.format('dd/MM/yyyy'),)}
Demo:
More information: Apache Groovy - Why and How You Should Use It

Trying to understand NSDatePicker

I'm desperately trying to understand swift's DatePicker. I have a need to select dates from Julian Day 0 (11/24/4714 BCE) to dates in the future. When I extract the DateComponents from the DatePicker, they do not appear to be a 'proleptic' gregorian calendar. For instance, by selecting 3/1/300 AD (or CE), the month and day are 2/29. This seems consistent with the Julian Calendar, a date I cannot select with the DatePicker's calendar set to iso8601 or gregorian. I am familiar with the date of adoption of the Gregorian calendar, and indeed this is where the discrepancies begin. But why won't it calculate the proleptic dates, or am I misunderstanding this. Extracting these components is necessary for calculating various quantities such as Julian Day or converting from one calendar to another. Even a suggestion of where to find the info would be appreciated.
---Edited to show code -----
#IBAction func calculate(_ sender: Any) {
var mycal = Calendar(identifier: .iso8601)
//var mycal = Calendar(identifier: .gregorian)
let picked_date:Date = datePicker.dateValue
let formatter1 = DateFormatter()
formatter1.locale = Locale(identifier: "en_US_POSIX")
formatter1.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let picked_format = formatter1.string(from: picked_date)
//print("picked_format: \(picked_format)")
let format_date = formatter1.date(from: picked_format)
var tz: String { return TimeZone.current.identifier }
let myzone = UTC.state == NSOnState ? tz : "GMT"
//let era = AD.state == NSOnState ? 1 : 0
mycal.timeZone = TimeZone(identifier: myzone)!
var comps = mycal.dateComponents([.year,
.month,
.day,
.hour,
.minute,
.second,
//.era,
//.nanosecond,
.timeZone],
from: format_date!)
print(comps.month!)
print(comps.day!)
Bottom line: The discrepancies in what was shown in DatePicker vs the 'elements' of the date object it produced (namely, YEAR, MONTH and DAY) were due wholly to a careless mistake I made writing the code: The failure to ensure that all the objects that dealt with dates were specified to the same Calendar. Initially, my DateFormatter and DateComponents objects were set to ".iso8601" and failing to specify a calendar for the DatePicker defaulted it to my locale, which meant ".gregorian". This produced a 10 day discrepancy in the date prior to Oct 15, 1582. Also: A DatePicker using the Gregorian calendar will allow you to select days from 5 Oct 1582 - 14 Oct 1582 (inclusive), just as I would expect from a proleptic calendar. A DatePicker using the ISO calendar will NOT allow dates in this range. Stepping down from 15 Oct 1582 by one day will result in the DatePicker showing 4 Oct 1582 ... not the result I would expect if it is based on the proleptic Gregorian.
Some caveats, though. Apple's documentation and the ISO standard itself lead me to believe that the ISO calendar was based on a proleptic Gregorian calendar. This proved to be untrue. You can repeat for yourself the following: Create a DatePicker specifying the ISO calendar and it will allow you to choose dates which do not exist in the Gregorian calendar, namely leap years for such years as 1500, 1400, 1300, 1100, 1000, etc. This is more in keeping with the ISO calendar behaving like the Julian Calendar prior to the adoption date. Indeed, the date discrepancies begin to narrow as the year number decreases because the ISO calendar is counting those years as leap years. The error becomes ZERO from 1 March 200 - 28 Feb 300 AD, exactly as one would expect of a Julian Calendar vs a proleptic Gregorian calendar. I don't know if I am misunderstanding how the ISO calendar is supposed to behave, or if this is a bug. Thanks to Willeke for leading me to the correct solution!

d3.js - Timestamp based on year and week

I have a column with data year&week. I would like to create a date axis based on this.
when i try to format the date, it is not working
I tried this:
var parseDate = d3.time.format("%Y-%W").parse;
d3.csv("temperatures_groups_2.csv", function(error, data) {
data.forEach(function(d,i) {
d.timestamp = parseDate(d.timestamp);
alert(d.timestamp);
d.temperature = +d.temperature;
}
});
i get null when the alert executes.
If i replace the same with d3.time.format("%Y-%m").parse, it works fine. It takes the month but not week no.
The csv contains data like this
timestamp,temperature
2013-01,19.5
2014-02,21.5
2015-03,20.5
2016-04,20.5
2017-05,21.25
The documentation says:
The following directives are not yet supported for parsing:
%U - week number of the year.
%W - week number of the year.
Hence you can't use D3 to parse these dates. You'll have to parse the date yourself or use another library, for example moment.js.
This works since version 3.2 and the documentation has been updated.
%U - week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
%W - week number of the year (Monday as the first day of the week) as a decimal number [00,53].
However, the format in your question won't work because the parser requires a specific date to be specified. E.g. by "%a". It would be nice to assume Sunday in the absence of a date specifier, but that's for another PR.

Year, Month, and Day parameters describe an un-representable DateTime Exception

I'm adding an object to a list within an ASP.NET MVC 3 application using the following code but one of the properties of the object is giving me difficulties.
ls.Add(new UserRoleModel { UserRoleId = 1, UserName = "Paul", InsertDate = new DateTime(05, 24, 2012),InsertProgram="sqlplus",InsertUser="sp22",Role="Implementation Co-corindator"});
This builds but when I go to the relevant page i get an Exception with the following type:
Exception Details: System.ArgumentOutOfRangeException: Year, Month, and Day parameters describe an un-representable DateTime.
I've tried removing the 0 in the month but I get the same exception.
The DateTime constructor you are calling accepts parameters in the order year, month, day.
You are providing them in the order month, day, year -- which ends up trying to assign meaningless values. The documentation is pretty clear on what the allowed values are and what happens if you pass 2012 for the "day" value.
I just ran into this and my issue was I was creating a date in February. I tried to do the following...
new Date(2013, 2, 30)
Since there is not a February 30th, the date failed to create. When I changed to
new Date(2013, 2, 28)
it worked fine.
if the InsertDate meant to be the date / time of creation you can just use the following
DateTime InsertDate = DateTime.Now;
You are using an Invalid datetime, like for month you may be passing 13,14 days more than 31
or something like that which is causing the issue.
i was having the same issue because i was trying to create a DateTime object with date set to 31 of April even though April only has 30 days.
Anyone having the same issue, make sure you are not making this mistake.
Simply you have to change the InsertDate into
InsertDate = new DateTime(Year,Month,Date);
It will solve your problem.
I was facing the same type of issue, where I was using a DateTimePicker in Winform Application. Where user can only pick only month and year and my code and UI was look like
Code
this.dtpMonth.CustomFormat = "MMMM yyyy";
this.dtpMonth.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.dtpMonth.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
this.dtpMonth.Location = new System.Drawing.Point(88, 24);
this.dtpMonth.Name = "dtpMonth";
this.dtpMonth.ShowUpDown = true;
this.dtpMonth.Size = new System.Drawing.Size(136, 22);
this.dtpMonth.TabIndex = 1;
And I was initializing the by this.dtpMonth=DateTime.Today; and this line cost me and error of current discussion.
Afterward, I have found that my date(DateTime.Today) was 31 July. So, when user want change the month to August it throws exception because August doesn't have date 31. Finally, I change my code into
dtpMonth.Value =new DateTime(DateTime.Today.Year, DateTime.Today.Month,1);
And worked for me.
The same exception I solved as:
DateTimePicker1.Value = DateSerial(Year(Now), Month(Now) + 1, 1)
For those who has this issue, make sure that date, which you try to create exists. For example, I had this problem, because was trying to create 29 feb at not leap year
if you got this error because you're trying to insert 29 days in a year that's not a leap year, then you can check the maximum allowed days first of that year as such:
if(DateTime.DaysInMonth(2024,2) == 29)
dt = new DateTime(2024, 2, 29);

Determine regional business days and weekend days of the week

In some countries weekend days are Friday/Saturday.
How can a Windows application find out weekend days of the user?
Wellll...I don't know of a "One function" answer to this. You're gonna need to know where they are somehow. If it's a webapp, you can trace their IP and figure out what country they are from. If it's a windows app, you're probably going to need to ask them (The clock only provides timezone information, and i can't figure out where else to grab a more fine-grained location from windows).
You can figure out what day it is with GetDayofWeek http://msdn.microsoft.com/en-us/library/1wzak8d0%28VS.80%29.aspx in MFC
DayofWeek if you hop to .Net http://msdn.microsoft.com/en-us/library/system.dayofweek.aspx
You'll need a lookup table with countries/what days they consider weekends..you'll probably have to construct this, but you can get a list of countries from: http://www.iso.org/iso/english_country_names_and_code_elements
That list is ISO 3166.
It's updated and should be your "one-stop-shop" for the listing. From there, you'll match "weekends" to the countries. http://en.wikipedia.org/wiki/Workweek might help in figuring out weekends/workweeks for countries.
The following code will provide whether or not it is considered the weekend, with an option for different cultures (where the weekend starts/ends on a different day):
/// <summary>
/// Returns true if the specified date is weekend in given culture
/// is in.
/// </summary>
public static bool IsItWeekend(DateTime currentDay, CultureInfo cultureInfo)
{
bool isItWeekend = false;
DayOfWeek firstDay = cultureInfo.DateTimeFormat.FirstDayOfWeek;
DayOfWeek currentDayInProvidedDatetime = currentDay.DayOfWeek;
DayOfWeek lastDayOfWeek = firstDay + 4;
if (currentDayInProvidedDatetime == lastDayOfWeek + 1 || currentDayInProvidedDatetime == lastDayOfWeek + 2)
isItWeekend = true;
return isItWeekend;
}
ICU project might help. It is designed for software internalization and globalization. C/C++ and Java version are available.
icu-project.org

Resources