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

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.

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");

System.DateTime comparison ('>') or ('<') does not give what I expected

I want to get files from a list for all the files whose filedate > today's cutOff - so, I have the following codelet
string[] MyFiles = Directory.GetFiles(MyConfig.pathTransmittedFiles, "*.adf")
.Where(file => new FileInfo(file).LastWriteTime > dtCutOff).ToArray();
I have a file whose LastWriteTime is "{11/3/2015 1:33:26 PM}" being picked up by my collection with dtCutOff == "{11/3/2015 1:33:26 PM}"! So '>' didn't seem to work.
First, I would try running it without the Where clause, just to make sure that all files you expect are indeed part of the initial array returned from Directory.GetFiles. It's entirely possible that date/time comparison is not the source of the discrepancy. It may be more related to the issue Ivan linked to in the question comments, or it may be permission related, or some other thing.
Next, be aware that DateTime violates SRP in that it has a Kind property, which is one of the three DateTimeKind enumeration values. It's either Local, Utc, or Unspecified.
In the case of DateTime.Now, the Kind will be DateTimeKind.Local. File.GetLastWriteTime also returns its value with local kind. Therfore, if you always derive your dtCutOff from DateTime.Now in the manner you showed in the question, then it will almost always be the correct comparison function.
The "almost" stems from the fact that DateTimeKind.Local can actually represent two different kinds under the covers. In other words, there are actually four kinds, but two of them are exposed by one. This is described as "DateTime's Deep Dark Secret" in Jon Skeet's blog post More Fun with DateTime, and is also mentioned in the comments in the .NET Framework Reference Source. In practice, you should only encounter this in the ambiguous hour during a fall-back daylight saving time transition (such as just occurred last Sunday 2015-11-01 in the US).
Now, to the more likely case that your dtCutOff is actually derived not from DateTime.Now, but rather from user input or database lookup or some other mechanism, then its possible that it actually represents the local time in some other time zone than the one on your local computer. In other words, if the dtCutOff has a Kind of DateTimeKind.Utc, then the value is in terms of UTC. If it has a Kind of DateTimeKind.Unspecified, then the value might be in terms of UTC, or the local time zone, or some other time zone entirely.
Here's the kicker: Comparison of two DateTime values only evaluates the value underlying the Ticks property. It does not consider Kind.
Since file times are absolute points in universal time (on NTFS anyway), then you really should use the File.GetLastWriteTimeUtc method, rather than the methods that work in local time.
There are two approaches you could use:
Load the modified property as UTC, using:
myResult.modified = File.GetLastWriteTimeUtc(myFile);
Populate dtOffset appropriately.
If you're loading from the current time, then use DateTime.UtcNow.
If you're loading from other input, ensure the value is converted to UTC to match the input scenario. For example, use .ToUniversalTime() if the value is in terms of the local time zone, or use the conversion functions in the TimeZoneInfo class if the value is in another time zone.
OR
Change your modified property to be a DateTimeOffset instead of a DateTime.
Load that using:
myResult.modified = new DateTimeOffset(File.GetLastWriteTimeUtc(myFile));
Define dtCutOff as a DateTimeOffset, and populate appropriately.
If you're loading from the current time, then use DateTimeOffset.UtcNow.
If you're loading from other input, ensure the offset is set to match the input scenario. Use TimeZoneInfo functions if you need to convert from another time zone.
DateTimeOffset has many advantages over DateTime, such as not violating SRP. It's always representing an absolute moment in time. In this scenario, it helps to know that comparison operators on DateTimeOffset always reflect that absolute moment. (In other words, it internally adjusts to UTC before doing the comparison.)
This code works:
var cutffDate = new DateTime(2015,1,1); // or whatever
var allFiles = Directory.GetFiles(MyConfig.pathTransmittedFiles, "*.adf");
var datedFiles = allFiles.Where(f => (new FileInfo(f)).LastWriteTime > cutffDate);
Update:
Since your issue seems to be a precision-related one you could change the comparison to:
const long precision = 10; // vary this as needed
allFiles.Where(f =>
(new FileInfo(f)).LastWriteTime.ToFileTime()/precision > cutffDate.ToFileTime()/precision);
Alternatively you could use ...LastAccessTime.Ticks/TimeSpan.TicksPerMillisecond
In addition to that you may need to convert all DateTime values to UTC (LastAccessTimeUtc and DateTime.UtcNow) to make sure it's not some weird timezone issue
Since the files were fed into the queue once a day so the scale of precision is not required down to a millisecond or something. So that one-second TimeSpan difference is acceptable to do the trick and make my case work.
string[] MyFiles = Directory.GetFiles(MyConfig.pathTransmittedFiles, "*.adf")
.Where(file => new FileInfo(file).LastWriteTime - TimeSpan.FromSeconds(1) > dtCutOff)
.ToArray();
Now my file with modified date "{11/3/2015 1:33:26 PM}" didn't go into my collection when my cutOffDate is "{11/3/2015 1:33:26 PM}" while my other file with modified date "{11/3/2015 1:33:27 PM}" have successfully passed into my collection as expected!! So, it works and that's how it should work after all these advises! Thanks ye-all.
Looks like your Where clause lambda might be incorrect. Try this.
string[] MyFiles = Directory.GetFiles(MyConfig.pathTransmittedFiles, "*.adf").Where(file => file.modified > dtCutOff).ToArray();

Wrong Month in Joda 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.

events (as a json feed), start end parameters unix timestamp, are different if I change my OS time zone

I'm using the fullcalendar plugin and would appreciate if someone can give me a hand.
I am getting json events through a PHP URL.
something like this:
$('#calendar').fullCalendar({ events: "/myfeed.php" });
So in my php page that returns the events, I am getting 3 GET parameters:
'_'
'start'
'end'
The start and end parameter, indicate the date in UNIX timestamp.
So far so good, the problem that occurs is that if I change the time zone on my OS. also change these parameters start and end, for the same query in the same day in the calendar.
the weirdest part is that it only happens in Mozilla Firefox.
in Google Chrome, this problem does not occur.
e.g.
I have set my time zone ((UTC-04: 00) Santiago)
I'm referring to the day 09.09.2012 on the agenda,
firebug shows me that these parameters are being sent to my php page
_ 1347245953581
end 1347246000
start 1347159600
but if I change the time zone from my OS to ((UTC-03: 00) Buenos Aires)
consulting on 09.09.2012 on the agenda,
are other parameters which are now sent to the PHP page.
_ 1347246338047
end 1347332400
start 1347246000
Being that it is the same day, are other start and end parameters which are sent to check for events.
There is an ignoreTimezone option on the fullcalendar that might help. I'm not sure if it affects the start/end time passed to the feeds.
http://arshaw.com/fullcalendar/docs/event_data/ignoreTimezone/
Another option is to convert the passed timestamp to a Date object and get the local data from the Date object afterwards and use that in your queries.
Convert a Unix timestamp to time in JavaScript
I know it is not the exact answer, but it might help you out a bit.
Here is a sample piece of PHP code to convert the passed timestamp into a local formatted date:
$startts = $_REQUEST["start"]; // original timestamp
$startdt = new DateTime('now', new DateTimeZone('Europe/Oslo') ); // setup a local datetime
$startdt->setTimestamp($startts); // Set the date based on timestamp
echo $startdt->format('Y-m-d H:i:s'); // Output local date and time

Flex- Time Zone Conversion

How to convert date and time to CDT time Zone in flex4
Regards,
Sushma
The Date object in Flash is always set to the computer's time settings. If the computer is already in the CDT timezone, then just getting any property from the object will be good. However, if you want to do a timezone 'conversion' into a timezone that the computer is not set to, you can get the UTC time and offset it like this:
var date:Date = new Date();
var timezone:int = -5;
date.hours = date.hoursUTC + timezone;
However, you're trying to get the actual CDT time, which only works during the summer in certain areas. For this, it's impossible for Flash to know exactly when that is UNLESS you code the exceptions (ie. if between this date and that date, do -6, else do -5) and you also need to know the actual location of the user (which is impossible through Flash unless the user gives you that info).
Can I ask why you need to know such a thing?

Resources