What is the value of the ISO 8601 duration `P1M` (in seconds)? - duration

Suppose I have an ISO 8601 duration, expressed as "P1M". Phrased colloquially, this means "one month." Is there a standard rule for converting this into a number of seconds, assuming the start date is not known?
For 30-day months, it might be 2,592,000.
For 31-day months, it might be 2,678,400.
In February, it might be 2,419,200 or it might be 2,505,600.
My gut says there's no way to resolve "one month" to an exact number of seconds without knowing context, and where those seconds are laid out on the calendar. But are there standard rules/conventions to calculate these durations in an abstract way?

From ISO 8601 documentation that I found (page 6 - http://xml.coverpages.org/ISO-FDIS-8601.pdf), it seems you are correct in that the number of seconds in a month cannot definitively be determined. However it does note that "In certain applications a month is regarded as a unit of time of 30 days", so depending on your application this may be a valid approach.
The distinction between "Calendar Time" (Years, Months, etc) and "Absolute Time" (Hours, Minutes, Seconds, etc) is sometimes an important one. As an example, some people might complain about having 13 mortgage payments some years if they paid every 30 days as opposed to every month.

You are right, an ISO 8601 duration is dependent of the context.
A duration is a period/an interval of time between two dates.
Example :
2020-01-01/2020-02-01 = P1M = P31D
2020-02-01/2020-03-01 = P1M = P29D
2019-02-01/2019-03-01 = P1M = P28D
If you want a fixed duration indepedent of the context, use the day notation P30D, P60D, P90D... instead.
The same applies for years :
2019-01-01/2020-01-01 = P1Y = P12M = P365D
2020-01-01/2021-01-01 = P1Y = P12M = P366D
If you can't have context information about a duration, for example P1M retrieved from database or given by user input, use by default today's context.
//What is a duration of one month in seconds ?
P1M = ? (no context)
//Use default context
Today = 2020-03-31
2020-03-31/P1M = 2020-03-31/2020-04-30
=> P1M = P30D
//A month contains 2 592 000 seconds

Related

How to convert a hex TimeDateStamp DWORD value into human readable format?

Can anyone explain how to convert a Hex TimeDateStamp DWORD value into human readable format?
I'm just curious as to how a value such as 0x62444DB4 is converted into
"Wednesday, 30 March 2022 10:31:48 PM"
I tried googling of course and could not find any explanation. But there are online converters available.
But I'm just interested in converting these values for myself.
Your value is a 32-bit Timestamp.
Your datetime value is a 32-bit Unix Timestamp: The number of seconds since 1/1/1970.
See https://unixtime.org/
In most programming languages you can work with the hexadecimal notation directly.
Implementation should not be done by one person alone, since a lot of engineering goes into it. Leap years, even leap seconds, timezones, daylight savings time, UTC... all these things need to be addressed when working with a timestamp.
I have added my rough calculation below as a demonstration. Definitely use an existing package or library to work with timestamps.
See the JavaScript code below for demonstration.
There I multiply your value by 1000 because JavaScript works in Milliseconds. But otherwise this applies the same to other systems.
let timestamp = 0x62444DB4;
let dateTime = new Date(timestamp * 1000);
console.log('Timestamp in seconds:', timestamp);
console.log('Human-Readable:', dateTime.toDateString() + ' ' + dateTime.toTimeString());
// Rough output, just for the time.
// Year month and day get really messy with timezones, leap years, etc.
let hours = Math.floor(timestamp/3600) % 24;
let minutes = Math.floor(timestamp/60) % 60;
let seconds = Math.floor(timestamp) % 60;
console.log('Using our own time calculation:', hours + ':' + minutes + ':' + seconds);

Strange format from JodaTime when calculating time difference with Java

I am trying to find the duration between two times with the below code:
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
System.out.println(airTime1);
System.out.println(startTime1);
Minutes difference = ((Minutes.minutesBetween(startTime1,airTime1)));
String differenceS = String.valueOf(difference);
System.out.println(differenceS);
LocalTime remaining1 = formatter.parseLocalTime(differenceS);
System.out.println(remaining1);
airTime1 & startTime1 are both localTime variables. difference should contain the duration between the two times. differenceS is a String representation of difference, as minutes cannot be converted to String.
When I enter times into the variables such as 12:00 & 13:00, the variables are recorded as: 12:00:00.000 & 13:00:00.000, but differenceS received a value of PT-60M, which obviously throws an error. Does anyone know why the minutes difference line could be calculating this value?
Thanks in advance!
The Minutes class of jodatime overwrites the toString() method in a way that returns a String in ISO8601 duration format as mentioned in the JavaDoc. This is exactly what your PT-60M represents. A duration of -60 minutes.
If you just want the raw minutes printed your code could look like this:
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
System.out.println(airTime1);
System.out.println(startTime1);
Minutes difference = Minutes.minutesBetween(startTime1,airTime1);
System.out.println(Math.abs(difference.getMinutes()));

Finding the day in which a given year begins

This question arose when I was trying to understand Sakamoto's algorithm for finding the day of a given date.
I found the working of the algorithm to be difficult to comprehend even after reading the following Stackoverflow answer
So, I decided to first solve a specific problem of finding the day in which a given year begins( Jan-1).
From the Sakamoto's algorithm, I just took the part of adding the additional days contributed by the leap and non-leap years.
My code is as follows:
public String getDay(String date)
{
String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
int day = Integer.parseInt(date.split("/")[0]);
int month = Integer.parseInt(date.split("/")[1]);
int year = Integer.parseInt(date.split("/")[2]);
year--; // to calculate the additional days till the previous year
int dayOfTheWeek = (year + year/4 - year/100 + year/400) % 7;
return days[dayOfTheWeek];
}
Thus, for the date "1/1/0001", it returns Sunday.
To verify its correctness, I implemented Sakamoto's algorithm and compared the results and my program's result always seems to be one day before the day returned by the Sakamoto's algorithm.
For the date "1/1/0001" my program returns Sunday, while Sakamoto's returns Monday.
So,
1) Does it mean that the Gregorian calendar started on Monday instead of Sunday??
2) If yes, does it mean I should add 1 to the result to get the right day or is my program logically incorrect?
Finally, I used TimeAndDate site's day calculator tool and "1/1/0001" starts on Saturday.
My final question is
3) On what day does the Gregorian calendar start?
Any light on the these questions is much appreciated.
Thanks,
What exactly is the point of reinventing the wheel?
Joda-Time is a de facto standard for date-time operations in Java, and it provides dayOfWeek method for its DateTime objects. See e.g. http://joda-time.sourceforge.net/userguide.html#Querying_DateTimes
If you are then still interested in details how to get the computation right, see https://github.com/JodaOrg/joda-time/blob/master/src/main/java/org/joda/time/chrono/BasicChronology.java#L538

Converting numbers/string to time - PROLOG

I am a beginner in prolog and was wondering if there was an easy way to convert numbers to time, for comparison.
For example:
The below two lists show bus name, capacity, time it arrives at city, time it departs city.
bus_info(bus1,150, 12:30, 14:30).
bus_info(bus2, 200, 16:00, 18:00).
passenger_info(mike, 21, 17:30). -shows name, age, and time available
I want to check which bus Mike can catch. The answer is bus 2, but how do I calculate this in prolog?
You're just comparing times for a given day so you don't need to convert the numbers to any kind of system time encoding. You only need, say "minutes past midnight" or something like that. For example, 12:30 would be (12*60)+30 minutes past midnight. And you can use that as your comparison units for a daily schedule.
To capture your hours and minutes to do this calculation, if you were to "ask" in Prolog:
bus_info(Bus, Num, StartHH:StartMM, EndHH:EndMM).
You would get two results:
Bus = bus1
Num = 150
StartHH = 12
StartMM = 30
EndHH = 14
EndHH = 30
And
Bus = bus2
Num = 200
StartHH = 16
StartMM = 0
EndHH = 18
EndMM = 0
To assign a numeric value of an expression in Prolog, you need the is predicate. For example:
StartTime is (StartHH * 60) + StartMM.
That basic information should get you started if you've learned how Prolog predicates basically work.

Are the Date, Time, and DateTime classes necessary?

What is the purpose of having Date and Time classes when there is a DateTime class that can handle both?
To summarize what the common ruby time classes are:
Time
This is the basic workhorse core ruby time class.
Has date and time attributes (year, month, day, hour, min, sec, subsec)
Based on floating-point second intervals from unix epoch (1970-01-01)
Can handle negative times before unix epoch
Can handle time arithmetic in units of seconds
Natively works in either UTC or "local" (system time zone)
There are really 3 kinds of Time object when it comes to dealing with time zones, let's look at a summer time to show DST:
utc = Time.utc(2012,6,1) # => 2012-12-21 00:00:00 UTC
utc.zone # => "UTC"
utc.dst? # => false
utc.utc? # => true
utc.utc_offset # => 0
local = Time.local(2012,6,1) # => 2012-06-01 00:00:00 -0700
local.zone # => "PDT"
local.dst? # => true
local.utc? # => false
local.utc_offset # => -25200
nonlocal = Time.new(2012,6,1,0,0,0, "-07:00") # => 2012-06-01 00:00:00 -0700
nonlocal.zone # => nil
nonlocal.dst? # => false
nonlocal.utc? # => false
nonlocal.utc_offset # => -25200
The last 2 look similar, but beware: you should not do arithmetic with a non-local Time. This is simply a time with a UTC offset and no zone, so it doesn't know the rules of DST. Adding time over the DST boundary will not change the offset and the resulting time-of-day will be wrong.
ActiveSupport::TimeWithZone
This one is worth mentioning here since it's what you use in Rails. Same as Time, plus:
Can handle any time zone
Respects DST
Can convert times between zones
I generally always reach for this when ActiveSupport is available as it takes care of all the time zone pitfalls.
Date
Has date attributes only (year, month, day)
Based on integer whole-day intervals from an arbitrary "day zero" (-4712-01-01)
Can handle date arithmetic in units of whole days
Can convert between dates in the ancient Julian calendar to modern Gregorian
Date is more useful than Time whenever you deal in whole days: no time zones to worry about! (I'm surprised this doesn't deal with the modern Persian calendar since it knows about the obsolete Julian calendar from centuries ago.)
DateTime
Has date and time attributes (year, month, day, hour, min, sec)
Based on fractions of whole-day intervals from an arbitrary "day zero" (-4712-01-01)
Can handle date arithmetic in units of whole days or fractions
Personally, I never have reason to use this: it's slow, it handles time without considering time zones, and it has an inconsistent interface. I find it leads to confusion whenever you assume you have a Time-like object, but it actually behaves like a Date instead:
Time.new(2012, 12, 31, 0, 0, 0) + 1 == Time.new(2012, 12, 31, 0, 0, 1)
DateTime.new(2012, 12, 31, 0, 0, 0) + 1 == DateTime.new(2013, 1, 1, 0, 0, 0)
Further, it has a meaningless "zone" attribute (note how non-local Time objects warn you that zone == nil), and you can't know anything else about it before turning it into a Time first:
dt = DateTime.new(2012,12,6, 1, 0, 0, "-07:00")
dt.zone # => "-07:00"
dt.utc? # => NoMethodError: undefined method `utc?'
dt.dst? # => NoMethodError: undefined method `dst?'
dt.utc_offset # => NoMethodError: undefined method `utc_offset'
Dealing with microseconds to check for rounding is also a little strange. You would think that because it doesn't have a usec attribute that it only deals in whole numbers, but you'd be wrong:
DateTime.now.usec # => NoMethodError: undefined method `usec'
DateTime.now.to_time.usec => 629399
In short, unless you're dealing with astronomical events in the ancient past and need to convert the Julian date (with time of day) to a modern calendar, please don't use DateTime. If anyone has an actual use case for this class, I'd love to read your comments.
I know there is an accepted answer but I have something to add. The Date class is a heavyweight, academic strength class. It can handle all sorts of RFC's, parse the strangest things and converts julian dates from thousand years ago to gregorian with the reform date of choice. The Time class is lightweight and it does not know of any of this stuff. It's cheaper and that shows up in a benchmark:
require 'benchmark'
require 'date'
Benchmark.bm(10) do |x|
x.report('date'){100000.times{Date.today} }
x.report('datetime'){100000.times{DateTime.now} }
x.report('time'){100000.times{Time.now} }
end
Result:
user system total real
date 1.250000 0.270000 1.520000 ( 1.799531)
datetime 6.660000 0.360000 7.020000 ( 7.690016)
time 0.140000 0.030000 0.170000 ( 0.200738)
(Ruby 1.9.2)
DateTime is a subclass of Date, so whatever you can do with Date can be done with DateTime. But as tadman and steenslag point out, DateTime is slower. See steenslag's answer for how much slower it is.
With respect to DateTime vs, Time, I found something here:
Time is a wrapper around Unix-Epoch.
Date (and DateTime) use rational and a "day zero" for storage. So Time is faster but the upper and lower bounds are tied to epoch time (which for 32bit epoch times is something around 1970-2040...while Date (and DateTime) have an almost infinite range but are terribly slow.
In short, DateTime is an all around superstar, and should be preferred in general, but if you want to optimize to the last bit, using Time can improve performance.
Another way of thinking of this is that Date and DateTime model time in terms of clocks and calendars, which is useful for describing times to users, and scheduling events. Having a Date without a time is nice for when you don't care about the time, and you don't want to think about time zones.
Time models time as a continuum, and is a wrapper around the Unix timestamp, which is just an integer. This is useful for all manner of internal applications where the computer doesn't care much whether a calendar boundary has been crossed, but just how many seconds (or milliseconds) have elapsed.
Yes. Date handles only the date for something, I.E., March 31, 1989. But it does not handle Time, for example, 12:30 PM.
DateTime, can handle both, March 31, 1989 12:30 PM EST.
Sometimes you don't need all parts of the DateTime. For example, you wanted to know when the use signed up for you website, Date would be useful here, because the time is eventually irrelevant.
In some cases you might want just the time. For example, if it's lunch time, you may want to tell the user your office is closed. At this point, the Data is irrelevant.
However, in most cases DateTime is used, because it can be used as either date, time, or both.

Resources