Wrong Month in Joda DateTime - datetime

When I run the following code (Java):
DateTimeFormatter d_t = DateTimeFormat.forPattern("dd/m/yyyy h:mm:ss aa");
String date = "27/3/2015 2:47:08 AM";
DateTime result = DateTime.parse(date, d_t);
I always get the result as: 2015-01-27T02:47:08.000+02:00
As you can see the month and the hours are incorrect.
Any suggestions?
Thanks

Month of year is written with a capital M as well as hour of day H.
Try
DateTimeFormat.forPattern("dd/M/yyyy H:mm:ss aa");

tl;dr
LocalDateTime.parse(
"27/3/2015 2:47:08 AM" ,
DateTimeFormatter.ofPattern( "d/M/uuuu h:m:s a" , Locale.US )
)
2015-03-27T02:47:08
java.time
Your input string seems especially odd. The hour does not have a padding zero but the second does? Strange, but it can be parsed using the modern java.time classes.
The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
You were inappropriately trying to store a date-time value lacking any offset or time zone information into a data type wielding a time zone.Parse your input string as a LocalDateTime since we have no indication of offset-from-UTC or time zone.
String input = "27/3/2015 2:47:08 AM";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "d/M/uuuu h:m:s a" , Locale.US );
LocalDateTime ldt = LocalDateTime.parse( input , f );
Dump to console.
System.out.println( input + " = " + ldt );
27/3/2015 2:47:08 AM = 2015-03-27T02:47:08
Be aware that a LocalDateTime is not a point on the timeline. It represents only a set of possible moments over a range of about 26-27 hours. It has no real meaning until you place the value in context, either applying an offset to get a OffsetDateTime or a full time zone to get a ZonedDateTime.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Related

Moment return the same value passed to it instead of utc value

Im trying to trasform a date to utc but moment return the same value i use.
for example
moment(date, 'YYYY-MM-DD HH:mm:ss').utc().format('YYYY-MM-DD HH:mm:ss')
if i use date = '2022-01-07 11:30:00' moment return 2022-01-07 11:30:00
do i have to set the timezone of the value first? why moment return the wrong value? it should return +3 hours that date.
You'll need to define the timezone in which the date is, then the offset will be as expected:
Example, using Europe/Amsterdam as timezone
const date = '2022-01-07 11:30:00';
const utc = moment(date, 'YYYY-MM-DD HH:mm:ss')
.tz('Europe/Amsterdam')
.utc()
.format('YYYY-MM-DD HH:mm:ss');
console.log(utc);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.32/moment-timezone-with-data.min.js"></script>
This will output 2022-01-07 10:30:00 since Amsterdam time is -1 compared to UTC.
Small side node, quoting MomentJS Project Status page
We now generally consider Moment to be a legacy project in maintenance mode. It is not dead, but it is indeed done.
In practice, this means:
We will not be adding new features or capabilities.
We will not be changing Moment's API to be immutable.
We will not be addressing tree shaking or bundle size issues.
We will not be making any major changes (no version 3).
We may choose to not fix bugs or behavioral quirks, especially if they are long-standing known issues.
The data you pass in doesn't have any indication of the timezone it's in, so moment is (I believe) assuming it's in utc already.
In related news, look into using the date-fns library instead of moment. Moment is getting old...
Moment github
Moment.js is a legacy project, now in maintenance mode. In most cases,
you should choose a different library.
This returns the same date since you never indicated any timezone
var time = moment("2013-08-26 16:55:00") //this creates time in my tz
You can set a timezone like this:
var time = moment("2013-08-26 16:55:00").tz("America/Los_Angeles");

Convert current mediaPlayer time to formated time in Android Studio using java

check my function below, its showing like this 124:45 *means it is not converting hours into minutes. Like this:
Kindly make changes in my below function that give me correct time.
private String formatedTime(int mCuurentPosition) {
String totalout="";
String totalnew="";
String seconds=String.valueOf(mCuurentPosition % 60);
String mints =String.valueOf(mCuurentPosition / 60);
totalout =mints + ":" + seconds;
totalnew=mints + ":" + "0" + seconds;
if (seconds.length()==1){
return totalnew;
}else {
return totalout;
}
java.time.Duration, desugaring and String.format()
private String formattedTime(int mCurrentPosition) {
Duration pos = Duration.ofSeconds(mCurrentPosition);
long hours = pos.toHours();
if (hours == 0) {
return String.format("%d:%02d", pos.toMinutes(), pos.toSecondsPart());
} else {
return String.format("%d:%02d:%02d",
hours, pos.toMinutesPart(), pos.toSecondsPart());
}
}
I haven’t got an Android development environment with me, so am not 100 % sure that desugaring can handle this, but I would certainly dare hope so. The toMinutesPart and toSecondsPart methods were introduced in Java 9. String.format() has been around since Java 1.5, so in any case let it do the formatting for you.
See the above method in action:
System.out.println(formattedTime(47));
System.out.println(formattedTime(4747));
Output is:
0:47
1:19:07
Question: Doesn’t java.time.Duration require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Similar questions (no strict duplicates, but loads of helpful information):
Convert number of seconds into HH:MM (without seconds) in Java
How can I “pretty print” a Duration in Java?
How do i format a java.time.Duration mm:ss
Other links:
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
Java 8+ APIs available through desugaring
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

How to handle Edm:DateTime form OData interface in SAPUI5 correct?

Is there a definition what values should be send in OData Edm:DateTime of a SAP Netweaver Gateway service?
Especially should it always be interpreted as UTC?
I assume the SAPUI5 library is smart enough to handle all this time zone problems automatically if the interface is correct defined -- question is, what is correct?
I would prefer to use some code like this, at client side:
new sap.m.DatePicker({
value : {
path : "BirthDate",
type : new sap.ui.model.type.Date
}
}),
How do you solve these problems?
Edit
Time zone handling seems still to be strange to me.
SAP Gateway Server sends in an Edm:DateTime following: 2015-04-16T00:00:00
Any time zone information is missing.
If I bind a date picker like this:
var oContent = new sap.m.DatePicker({
value : {
path : "Date",
type : new sap.ui.model.type.Date({
style: "short",
})
}
})
I got the following output: 16.04.15 (seems to be correct).
Binding a date picker without type information shows: Thu Apr 16 2015 02:00:00 GMT+0200 (Mitteleuropäische Sommerzeit)
If I change the date with the date picker to 17.04.15 the second line is:
Fri Apr 17 2015 00:00:00 GMT+0200 (Mitteleuropäische Sommerzeit)
Please note the difference in time (2 hours missing).
If I send it to the server I got Edm.DateTime == 2015-04-16T00:00:00
Control shows:
Thu Apr 16 2015 02:00:00 GMT+0200 (Mitteleuropäische Sommerzeit)
If I use
new sap.m.DatePicker({
value : {
path : "Date",
type : new sap.ui.model.type.Date({
style: "short",
UTC: true
})
}
})
Data seems to be correct (the 2 hours are not missing after picking a new date).
I am asking me, is there any definition what type of data gateway will send?
If the timezone is missing inside the Edm.DateTime information how should a client work correct? Especially if clients are in different time zones available?
Strange enough I have a similar problem by using a filter. But there the UTC flag seems not working.
Anyone with some experience on that topic? Or any hints to a good documentation?
* https://sapui5.netweaver.ondemand.com/sdk/#docs/guide/91f3070d6f4d1014b6dd926db0e91070.html
Says more or less "take care" but not how :-/
Further information
I detected the same question on SAP network (http://scn.sap.com/thread/3574419). Not sure if the given answer is correct. Looks like hacking around in meta-data which should not be required?
I am still searching for a solution to this problem
I detected different handling of data in case of binding and filter usage.
I can't answer with regard to SAP, as I am not familiar. But I can provide some insights based on OData.
The Edm:DateTime type is based on the W3C XML Schema xs:dateTime, which is in-turn based on ISO8601. Both XML Schema and ISO8601 state that times without a time zone are to be considered "local time". That is, local to someone. Whose "local" it is intentionally undefined.
From W3C XML Schema §3.2.7:
"Local" or untimezoned times are presumed to be the time in the timezone of some unspecified locality as prescribed by the appropriate legal authority
From ISO 8601 3rd Edition §4.3.2:
The zone designator is empty if use is made of local time ...
Consider your example of 2015-04-16T00:00:00. The only way to know what exact moment in time this refers to is to have some additional context applied. In the case of a birthday, this could be the time zone where the person is currently located (where they celebrate their birthday, not where they are born). Or, it could be some arbitrary location if the person's location is unknown - perhaps the time zone of the person using the system.
Therefore, the interpretation of the value is where the time zone is being applied. In your case, it would appear that some local time zone is being applied during deserialization.
Also consider that a birthday is better represented by just a calendar date, rather than midnight on a date. The Edm:Date type is better suited for this. For other types, especially if you know that the value is UTC or in a specific time zone, then Edm:DateTimeOffset is more appropriate.
Also recognize that the Edm:DateTime type was dropped from OData spec in version 4.0. Many (including myself) consider this a mistake. I'm not sure if this affects you or not, but you should be aware.
Hope that helps.
Use type sap.ui.model.type.Date({ oFormatOptions:{ style: "short", UTC: true} }) this will retain your date as it is sent by server
Could you try binding the date path to dateValue instead of value.
It should automatically interpret Edm:DateTime.
new sap.m.DatePicker({
dateValue : "{BirthDate}"
})

Using the current date in a Gatling test

I am trying to load test an application using Gatling, and the application needs the current date to be inserted into the test:
.formParam("dateCreation", "07/01/2015 16:48:04")
If it's hard coded it seems to upset the application being tested.
How can I generate the above string at the time of each request? (It's European format - day/month/year)
Scala isn't my strong point. I'm using Gatling 2.0.3.
Use a modern Java date API, like joda-time, or JDK8's DateTime API.
With either API, you'll have to:
first build a formatter for the desired pattern ("dd/MM/yyyy hh:mm:ss"). Only build this once and for all as those are threadsafe (unlike Java's SimpleDateFormat).
instead of passing a hard coded value, pass a Session function that fetch the current date and format it. It will look like (pseudo code):
val formatter = ???
.formParam("dateCreation", session => formatter.format(now()))
This way, the formatted date will be computed for each execution of this request.

What languages do date, time, and calendar operations really well? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
This is probably too much to ask, but is there any language that does a really terrific job of representing time and date operations? I'll grant straight away that it's really hard to write a truly great time library. That said, are there any widespread languages that have one? Basically, I want something that handles time and date as comprehensively as modern regular expression libraries do their jobs. Everything I've seen so far in Python and Java omits one or more pretty important pieces, or makes too many things hard.
At least this should be intuitive to do:
find the number of days between two given dates, number of minutes between two given minute periods, etc.
add and subtract intervals from timestamps
allow simple conversion between timezones, with Daylight Saving Time changes by region automatically accounted for (given that there's an accurate supporting database of regional settings available)
get the period that a given timestamp falls into, given period granularity ("what calendar day is this date in?")
support very general string-to-date conversions (given a pattern)
Further, if there's a Java-style Calendar/GregorianCalendar setup, the general Calendar class should be accommodating toward subclasses if I need to roll my own Hebrew, Babylonian, Tolkien, or MartianCalendar. (Java Calendars make this pointlessly hard, for example.)
I am completely language-agnostic here. It's fine if the thing chokes on computing ambiguous stuff like "how many minutes are there between 2002 and next Valentine's Day?"
How about .NET's DateTime? (You can pick your language within the framework)
Are you looking for something like PHPs strtotime? That will give you the unix timestamp of almost anything you can throw at it.
From the php site:
<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>
.NET's date classes require much more arcane fiddling with DateTimeFormatInfo and the like to parse date strings that aren't nearly as complicated as strtotime can handle.
PHP provides a DateTime class and a DateTimeZone class as of PHP 5, but they're both quite poorly documented. I still mostly use unix timestamps and the date, time and strtotime functions as I haven't fully come to grips with the new objects.
The following links attempt to flesh out DateTime and DateTimeZone a bit better:
http://laughingmeme.org/2007/02/27/
http://maetl.coretxt.net.nz/datetime-in-php
For Java, I highly recommend the Joda Date/Time library.
You might want to check the Date::Manip Perl module on CPAN.
There is a really cool programming language called Frink. It supports pretty much every unit ever invented, every physical or mathematical constant, timezones, bla bla bla …
It even has a web interface and a Java Applet.
Some of your challenges above:
find the number of days between two given dates, number of minutes between two given minute periods, etc.
How many days till Christmas: # 2008-12-25 # - now[] -> days
How long since noon: now[] - # 12:00 # -> minutes
add and subtract intervals from timestamps
When was my million minutes birthday: # 1979-01-06 # + 1 million minutes
allow simple conversion between timezones, with Daylight Saving Time changes by region automatically accounted for (given that there's an accurate supporting database of regional settings available)
When did the Beijing Olympics start in London: # 2008-08-08 08:08 PM China # -> London
support very general string-to-date conversions (given a pattern)
Define a new date format: ### dd.MM.yyyy ###
Parse: # 18.09.2008 #
Frink integrates nicely with Java: it can be embedded in Java applications and Frink programs can call Java code.
I like .NET for this. It provides good Date/Time manipulation, with the DateTime and Timespan classes. However, most date/time stuff is fairly simple in any language which will give you a unix timestamp to work with.
PHP is not half bad.
// given two timestamps: $t1, and $t2:
// find the number of days between two given dates, number of minutes
// between two given minute periods, etc.
$daysBetween = floor(($t2 - $t1) / 86400); // 86400 = 1 day in seconds
$hoursBetween = floor(($t2 - $t1) / 3600); // 3600 = 1 hour in seconds
// add and subtract intervals from timestamps
$newDate = $t1 + $interval;
// allow simple conversion between timezones, with Daylight Saving Time
// changes by region automatically accounted for (given that there's an
// accurate supporting database of regional settings available)
// See PHP's Calendar functions for that
// http://au2.php.net/manual/en/book.calendar.php
// It not only supports basic stuff like timezones and DST, but also
// different types of calendar: French, Julian, Gregorian and Jewish.
// get the period that a given timestamp falls into, given period
// granularity ("what calendar day is this date in?")
if (date("d", $t1) == 5) // check if the timestamp is the 5th of the month
if (date("h", $t1) == 16) // is it 4:00pm-4:59pm ?
// support very general string-to-date conversions (given a pattern)
// strtotime() is magic for this. you can just type in regular english
// and it figures it out. If your dates are stored in a particular format
// and you want to convert them, you can use strptime()
You gotta give it some kudos for having a function to tell what date Easter is in a given year.
For C++, there's Boost.Date_Time.
java.time
The industry-leading date-time framework is java.time, built into Java 8 and later, defined by JSR 310.
The man leading this project is Stephen Colebourne. He also led its predecessor, the very successful Joda-Time project. The lessons learned with Joda-Time were applied in designing the all-new java.time classes. By the way, Joda-Time was ported to .Net in the NodaTime project.
find the number of days between two given dates,
Use the Period class to represent a span-of-time in granularity of years-months-days.
LocalDate start = LocalDate.of( 2019 , Month.JANUARY , 23 ) ;
LocalDate stop = LocalDate.of( 2019 , Month.MARCH , 3 ) ;
Period p = Period.between( start , stop ) ;
Or if you want just want a total count of days, use ChronoUnit.
long days = ChronoUnit.DAYS.between( start , stop ) ;
number of minutes between two given minute periods, etc.
Use Duration class to represent a span-of-time in granularity of days (24-hour chunks of time unrelated to calendar), hours, minutes, seconds, fractional second.
Instant start = Instant.now() ; // Capture the current moment as seen in UTC.
…
Instant stop = Instant.now() ;
Duration d = Duration.between( start , stop ) ;
If you want total number of minutes elapsed of the entire span-of-time, call toMinutes.
long elapsedMinutes = d.toMinutes() ;
add and subtract intervals from timestamps
You can do date-time math using the Period and Duration classes mentioned above, passing to plus & minus methods on various classes.
Instant now = Instant.now() ;
Duration d = Duration.ofMinutes( 7 ) ;
Instant later = now.plus( d ) ;
allow simple conversion between timezones, with Daylight Saving Time changes by region automatically accounted for
The ZoneId class stores a history of past, present, and future changes to the offset used by people of a specific region, that is, a time zone.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ; // Get the current date as seen by the people of a certain region.
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
We can use the ZoneId to adjust between zones. First, let's get the current moment as seen in UTC.
Instant instant = Instant.now() ;
Apply a time zone for the time zone in Tunisia. Apply a ZoneId to the Instant to yield a ZonedDateTime object. Same moment, same point on the timeline, but a different wall-clock time.
ZoneId zTunis = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdtTunis = instant.atZone( zTunis ) ;
Let us see the same moment as it would appear to someone in Japan who is looking up at the clock on their wall.
ZoneId zTokyo = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdtTokyo = zdtTunis.withZoneSameInstant( zTokyo ) ; // Same moment, different wall-clock time.
All three objects, instant, zdtTunis, and zdtTokyo all represent the same moment. Imagine a three-way conference call between someone in Iceland (where they use UTC), someone in Tunisia, and someone in Japan. If each person at the same moment looks up at the clock and calendar on their respective wall, they will each see a different time-of-day on their clock and possibly a different date on their calendar.
Notice that java.time uses immutable objects. Rather than change (“mutate”) an object, return a fresh new object based on the original’s values.
(given that there's an accurate supporting database of regional settings available)
Java includes a copy of tzdata, the standard time zone database. Be sure to keep your JVM up-to-date to carry current time-zone definitions. Unfortunately, politicians around the globe have shown a penchant for redefining the time zone(s) of their jurisdiction with little or no advance warning. So you may need update the tzddata manually if a time zone you care about changes suddenly.
By the way, your operating system likely carries its own copy of tzdata as well. Keep that fresh for your non-Java needs. Ditto for any other systems you may have installed such as a database server like Postgres with its own copy of tzdata.
get the period that a given timestamp falls into, given period granularity ("what calendar day is this date in?")
By “calendar day”, do you mean day-of-week? In java.time, we have DayOfWeek enum that predefines seven objects, one for each day of the week.
DayOfWeek dow = LocalDate.now( z ).getDayOfWeek() ;
By “calendar day”, do you mean the day of the year (1-366)?
int dayOfYear = LocalDate.now( z ).getDayOfYear() ;
By “calendar day”, do you mean a representation of the year-month?
YearMonth ym = YearMonth.from( today ) ; // `today` being `LocalDate.now( ZoneId.of( "Pacific/Auckland" ) )`.
Perhaps month-day?
MonthDay md = MonthDay.from( today ) ;
support very general string-to-date conversions (given a pattern)
You can specify a custom formatting pattern to use in parsing/generating string that represent the value of a date-time object. See the DateTimeFormatter.ofPattern method. Search Stack Overflow for more info, as this has been handled many many times.
If your string is properly formatted by the localization rules for a particular culture, you can let java.time do the work of parsing without bothering to define a formatting pattern.
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( locale ) ;
String output = LocalDate.now( z ).format( f ) ;
if there's a Java-style Calendar/GregorianCalendar setup
The Calendar and GregorianCalendar classes bundled with the earliest versions of Java are terrible. Never use them. They are supplanted entirely by the java.time classes, specifically the ZonedDateTime class.
accommodating toward subclasses if I need to roll my own Hebrew, Babylonian, Tolkien, or MartianCalendar. (Java Calendars make this pointlessly hard, for example.)
Many calendaring systems have already been implemented for java.time. Each is known as a chronology. The calendaring system commonly used in the West and in much business around the globe, is the ISO 8601 chronology. This is used by default in java.time, java.time.chrono.IsoChronology.
Bundled with Java you will also find additional chronologies including the Hijrah version of the Islamic calendar, the Japanese Imperial calendar system, Minguo calendar system (Taiwan, etc.), and the Thai Buddhist calendar.
You will find more chronologies defined in the ThreeTen-Extra project. See the org.threeten.extra.chrono package for a list including: IRS/IFRS standard accounting calendar, British Julian-Gregorian cutover calendar system, Coptic Christian calendar, the Discordian calendar system, Ethiopic calendar, the International Fixed calendar (Eastman Kodak calendar), Julian calendar, and more.
But if you need some other calendar, java.time provides the AbstractChronology to get you started. But do some serious web-searching before embarking on your own, as it may already be built. And all the above listed chronologies are open-source, so you can study them for guidance.
"how many minutes are there between 2002 and next Valentine's Day?"
LocalDate date2002 = Year.of( 2002 ).atDay( 1 );
MonthDay valentinesHoliday = MonthDay.of( Month.FEBRUARY , 14 );
ZoneId z = ZoneId.of( "America/Edmonton" );
LocalDate today = LocalDate.now( z );
LocalDate valDayThisYear = today.with( valentinesHoliday );
LocalDate nextValDay = valDayThisYear;
if ( valDayThisYear.isBefore( today ) )
{ // If Valentine's day already happened this year, move to next year’s Valentine's Day.
nextValDay = valDayThisYear.plusYears( 1 );
}
ZonedDateTime start = date2002.atStartOfDay( z );
ZonedDateTime stop = nextValDay.atStartOfDay( z );
Duration d = Duration.between( start , stop );
long minutes = d.toMinutes();
System.out.println( "From start: " + start + " to stop: " + stop + " is duration: " + d + " or a total in minutes: " + minutes + "." );
LocalDate date2002 = Year.of( 2002 ).atDay( 1 );
MonthDay valentinesHoliday = MonthDay.of( Month.FEBRUARY , 14 );
ZoneId z = ZoneId.of( "America/Edmonton" );
LocalDate today = LocalDate.now( z );
LocalDate valDayThisYear = today.with( valentinesHoliday );
LocalDate nextValDay = valDayThisYear;
if ( valDayThisYear.isBefore( today ) )
{ // If Valentine's day already happened this year, move to next year’s Valentine's Day.
nextValDay = valDayThisYear.plusYears( 1 );
}
ZonedDateTime start = date2002.atStartOfDay( z );
ZonedDateTime stop = nextValDay.atStartOfDay( z );
Duration d = Duration.between( start , stop );
long minutes = d.toMinutes();
System.out.println( "From start: " + start + " to stop: " + stop + " is duration: " + d + " or a total in minutes: " + minutes + "." );
When run.
From start: 2002-01-01T00:00-07:00[America/Edmonton] to stop: 2020-02-14T00:00-07:00[America/Edmonton] is duration: PT158832H or a total in minutes: 9529920.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I've been quite happy with the PEAR Date class for PHP. It does everything you're asking about, I believe, with the exception of multiple calendars, although there's also Date_Human, which could be a template for that sort of thing.
Also, I haven't worked with it yet, but Zend_Date, also for PHP, looks like it will work well for most of what you want. Zend_Date has the advantage of being based on Unix timestamps and the fact that the bulk of Zend Framework classes are intended to be easy to extend. So most likely you could quickly add support for your other date systems by extending Zend_Date.
Perl's DateTime library is without a doubt the best (as in most correct) library for handling datetime math, and timezones. Everything else is wrong to varying degrees. (and I say this having written the above referenced blog post on PHP's DateTime/DateTimeZone libraries)
My personal favourite would be Ruby with Rails' ActiveSupport.
start_time = 5.months_ago.at_end_of_week
end_time = 6.months.since(start_time)
It supports all of the features you've mentioned above with a similar DSL (domain specific language)
PHP Date function is fantastic and has lots of helpful functions (link: php.net/date )
.NET is not bad in it's latest releases plus i like the fact you can add a reference to a secondary language and mix and match the code in your project. So you could use C# and VB functions within the same class.
I agree that Java SDK has a terrible implementation of datetime library. Hopefully JSR 310 will fix this problem in Java 7. If you can't wait for Java 7, I would recommend the precursor to JSR-310, Joda Time.
I agree that Ruby on Rails implementation in ActiveSupport is an excellent implementation that gets the basics right.
Ruby has excellent support, actually. Check out this page. Really great support for turning strings into dates, dates into strings, doing math on dates, parsing "natural language" strings like "3 months ago this friday at 3:45pm" into an actual date, turning dates into strings so you can do stuff like "Sam last logged in 4 days ago" or whatever...
Very nifty.

Resources