Imagine there are two labels on a webpage both displaying a date. How would you find out which is the greater date taking into account what the users locale is.
Say Label 1 : 04/11/2009 Label 2: 09/10/2009
If it were in the US Label 2 > Label 1
If it were the UK Label 1 > Label 2
The date constructor ignores locale information so var d = new Date('04/11/2009') will always be the 11th April 2009 rather than the 4th November 2009 no matter the locale. Does anyone know any tricks to get around this? Any libraries worth checking out?
(the only wayout i can see at the moment is get the locale info using js and then parse the label so i can create a date object with another constructor but this seems to much for a supposedly simple problem?Furthermore this is not going to work well with lots of locales)
Recommend using a library like Globalize.js or Date.js
Related
I understand that getMonth() is zero indexed so, for example, June is 5. But I'm getting that it's 'off' by 2 in some situations.
myDate = new Date(1622513190000)
month = myDate.getMonth()
console.log(myDate)
console.log(month)
Returns:
2021-06-01T02:06:30.000Z
4
Anyone have an idea why this is returning 4 and not 5? I'm using node v14.15.5 and am getting the expected result for other dates (September is 8, August is 7)
Thanks!
Hi and welcome here :)
Working with dates and timezone is a bit tricky, everyone here can attest it. For general information, I suggest you to read this article about Coordinated universal time.
The Z you can see in myDate value means Zulu time, military name for UTC±00:00, the reference timezone. ±00:00 represents an eventual offset with the Zulu time.
After having gone crazy about this question, I advice you to :
always get and store dates in Zulu format, and then compute time lapse with them
you can show users local dates, but it's only to display them. If you have to compute with a user input, first get the UTC equivalent (as #RobG advised).
Good luck ! :)
How can I convert a relative date/time string to a real date/time in Javascript (can use libraries)
For example, the user will input into an edit field any of the following examples (among others):
THIS IS THE INPUT:
2 weeks ago
Last 3 weeks
24 hours ago
Last 4 months
Last week
Last monday
So, taking now/todays datetime as a starting point, I need to get the date/time they are referring to.
So is today is 2018-04-06 11:19 and they enter '1 week ago' or 'a week ago' then I need a routine which will return
'2018-03-30 11:19'
as the OUTPUT
I know about moment.js and how to use that to change a date/time/moment to a relative datetime, but I need it done the other way around, - to change a relative date string to a date/time.
EDIT:
I have now found :
- https://github.com/wanasit/chrono
which seems to solve the problem.
https://github.com/wanasit/chrono This library seems to provide exactly as was requested in the OP. The input is a relative date in Natural Language (almost) and the output is a date.
Given a datestring, how can I get the format string describing that datestring?
Put another way, how can I get the format string that Date() or MomentJS (might be different for each, that's fine) would use to parse that datestring if one didn't pass an explicit format to use?
So given '2016-01-01' it should output something like 'YYYY-MM-DD', for example.
(I am aware this is a simple question and may have an answer somewhere, but it is difficult to word concisely, so I could only find questions and answers about how to parse datestrings or how to display dates. None about how to output the format itself.)
Consolidating information from Matt Johnson's answer, some comments, and my own contribution.
With Moment.js (version 2.10.7+), you can use the Creation Data API. Something like this in Node.js:
moment('2016-01-01 00:00:00').creationData().format
outputs
'YYYY-MM-DD HH:mm:ss'
Just as any date parsing is, there is ambiguity about the format of many datestrings due to things such as locale (the order of months and days are switched between the US and Europe, for example). But the above method is sufficient for me.
You can't, without having additional information, such as the locale. For example, 01/12/16 could be Jan 12, 2016, December 1, 2016, or December 16, 2001.
Even when you know the locale, there are several places in the real world where more than one date format is used, depending on context.
See https://en.wikipedia.org/wiki/Date_format_by_country
However, if you are just trying to determine which one of multiple known formats was used to parse the input string, moment has an API for that called Creation Data. For example:
var m = moment("2016/06/10", ["YYYY-MM-DD", "MM/DD/YYYY"], true);
var f = m.creationData().format; // "MM/DD/YYYY"
I use the below code to format date time in iso format using java (I'm reducing 1 min from current time) and get the output as this "2016-03-17T11:38:21.xxxZ" < x represent some numbers> i want this to compare with the time which have mentioned in the DB.
Person who build that data insert query, he used javascript to get the time and format it in iso.
Date inside the DB is looks like this "2016-03-17T06:09:21.530Z" and its actual time is "11:39:21 GMT+0530 (India Standard Time)" which is similar to my current time but I'm comparing these two dates as string. and get 1min early data from DB.In that case i can't get an out put because as strings these two aren't match. can anybody recomand a solusion ?
I use OrientDB
Java Code
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Calendar date = Calendar.getInstance();
long t = date.getTimeInMillis();
date.setTimeInMillis(t);
date.set(Calendar.MINUTE, date.get(Calendar.MINUTE) - 1);
String time1minEarly = df.format(date.getTime());
Using Calendar.set() and Calendar.get() does not modify the date in a way you intend:
This will modify the minutes field in your case. So subtracting "1" will reduce the minute but not give a viable date for cases where minute initially is zero.
You may just subtract a minutes of milliseconds from your "t" variable to get a true minute offset.
And for ease of use you might also consider following advise from #Prashant and using LocalDateTime class from joda library.
Thanks Everybody for your support.
I figure out How to do this. it's pretty easy. Both #rpy and #Prashant are correct. Calendar is not suitable for solve my issue. Also LocalDateTime too. but it did help me to figure out the correct way.
#rpy and #Prashant they both did miss one thing that the javascript time represent the UTC time. that's the issue. (it's 5.5 hours behind compared to my location) so, I figure out this below code. it did what i wanted to do.
It's pretty easy. all you have to do is provide your zone id.
(You can get Zone id using this code : go to the link - http://www.javadb.com/list-possible-timezones-or-zoneids-in-java/)
Also you can choose so many formats by changing "DateTimeFormatter" value.
ZoneId UTCzoneId = ZoneId.of("UTC");
ZonedDateTime time1minEarly = ZonedDateTime.now(UTCzoneId).minusMinutes(1);
String UTCtime1minerly = time1minEarly.format(DateTimeFormatter.ISO_INSTANT);
Out put is similar to this : "2016-03-17T10:39:21.530Z"
(- UTC time at that time : 2016-03-17T10:40:21.530Z)
It appears I can't use the javascript Date object as it inherintly defaults to US dates when you initialise with a datestring. There is no way of passing any culture information to the date object
I.e. No matter what the clients locale settings are
var d = new Date("08/10/2009") will always create a date object representing the 10th August 2009 rather than the 8th October 2009 if the clients locale was the UK.
So given that my requirement is to be able to add/subtract days/months/years easily is there a clever way of doing this easily without the Date object
All i need to do is add a day to a date (or a string representation of a date). so if my code detects the locale setttings are in the US, when it sees a string like "10/08/2009" it whacks it up to "10/09/2009" but if it had detected it was in the UK it would have know it a uk string representation of a date and whacked it up to "09/10/2009"
For date manipulation and localization on JavaScript I always recommend the DateJS library.
This library abstracts the use of Date objects, has a very good localization options, powerful date parsing and formatting, and it also has a very nice fluent API.
If you know you are getting input formatted dd/mm/yyyy you can easily assemble the correct date.
function britDay(D){
D= D.match(/\d+/g);
return new Date(+D[2], D[1]-1, +D[0]);
}
toLocaleDateString will return the date in the format expected by the user.
Relying on the user input that obeys particular formatting rules is optimistic-
which is why most sites use separate, labeled inputs or select fields for the month, date and year.
You probably know that it's easy to add one day to a date, just add 86,400 * 1000 milliseconds to the date. It sounds like displaying in your locale is the issue; does Date.toLocaleString() not do the right thing for you?
dojo.date.locale.parse will be able to parse a formatted string according the locale of your choice. It has a table of cultural data based off unicode.org/cldr. See this article for more information.