I'm building a schedule calendar in React and wondering what's the best way to extract a key from a js Date object? I'm already using the date-fns library but haven't seen anything about ids in their documentation.
to be clear, each date only appears once in the list so I'm looking for the fastest way to get a unique key out of a date, without using the object reference.
So far I'm using date.valueOf() or format(date, 'yyyy-mm-dd') although I feel that might be overkill since it might be recalculated every render.
I've got trivial question for which I can't find simple answer - how can I format Date object in order to get it in format I need? For example, "20.01.2014". I know about moment.js library but I must do it using only native JS. Please, give me answer. Thanks!
You use the getHours, getMinutes, and getSeconds (or getUTCHours, getUTCMinutes, and getUTCSeconds) methods on your Date instance, which give you numbers, and then do the formatting with string manipulation.
I've spent literal hours searching the web for a JS library or a Node module that does just one thing: interpret user-input dates of all kinds (just english is fine) and converts them to a standard date.
For example, it should be able to recognize and convert the following into actual dates:
tomorrow
in a year
last week
in 8 hours
in 4 months
8 8 90
65
Sugar.js does this, however I don't want all its other features, and it extends native objects. Moment.js deprecated its ability to do this as they consider it too opinionated - fine.
One would think someone made a library for this. Does anyone know of any?
In cases like this where a library provides a functionality that I need but I do not need the entire library, I will just strip out the portion of the library that I need.
Sugar.js actually provided a customize option, so this is even easier to do.
http://sugarjs.com/customize
Additionally if you use bower or npm for your package management, there is already a package that just has the Date functions from Sugar.js:
https://github.com/fiznool/sugar-date
I'm including the date.js library in my site because I need its functionality.
I have just realized, though, that the standard Javascript parse() method is overwritten by it.
I'm trying to build a line chart in Highcharts, and the data series wants the first element to be be in milliseconds (their demos show them using the Date.UTC() method to achieve this, but my data is returned in a different format).
Short of doing a bunch of string manipulation to put my data into a format that Date.UTC will recognize, is there another way of getting the standard Javascript parse() functionality while date.js is loaded?
I know this isn't a direct solution to your problem, but it may help anyway.
If you want a fully featured date library that doesn't modify the native Date object, I wrote one called Moment.js.
It provides a lot of the things that DateJS provides (formatting, parsing, manipulation, timeago, i18n, etc), but it's smaller, faster, and doesn't ruin the native date prototype.
https://github.com/timrwood/moment
Nope, this is the intended design of date.js. It adds to the "prototype" of the Date object. Some people hate that, some people like it - but you've uncovered one of the drawbacks of this design.
You can tell Highcharts to not use UTC date:
Highcharts.setOptions({
global: {
useUTC: false
}
});
You should do this before you create the chart. Then you won't have to worry about converting your dates to UTC, it will be easier.
after I asked the question, I went ahead and did it this way:
d = Date.parse(data);
y = d.getFullYear();
m = d.getMonth();
d = d.getDate();
dUTC = Date.UTC(y, m, d);
but will now try your suggestions.
Let's say I have a date that I can represent in a culture-invariant format (ISO 8601).
I'll pick July 6, 2009, 3:54 pm UTC time in Paris, a.k.a. 5:54 pm local time in Paris observing daylight savings.
2009-07-06T15:54:12.000+02:00
OK... is there any hidden gem of markup that will tell the browser to convert that string into a localized version of it?
The closest solution is using Javascript's Date.prototype.toLocaleString(). It certainly does a good job, but it can be slow to iterate over a lot of dates, and it relies on Javascript.
Is there any HTML, CSS, XSLT, or otherwise semantic markup that a browser will recognize and automatically render the correct localized string?
Edit:
The method I am currently using is replacing the text of an HTML element with a localized string:
Starting with:
<span class="date">2009/07/06 15:54:12 GMT</span>
Using Javascript (with jQuery):
var dates = $("span.date", context);
// use for loop instead of .each() for speed
for(var i=0,len=dates.length; i < len; i++) {
// parse the date
var d = new Date(dates.eq(i).text());
// set the text to the localized string
dates.eq(i).text(d.toLocaleString());
}
From a practical point of view, it makes the text "flash" to the new value when the Javascript runs, and I don't like it.
From a principles point of view, I don't get why we need to do this - the browser should be able to localize standard things like currency, dates, numbers, as long as we mark it up as such.
A follow up question: Why do browsers/the Web not have such a simple feature - take a standard data item, and format it according to the client's settings?
I use toLocaleString() on my site, and I've never had a problem with the speed of it. How are you getting the server date into the Date object? Parsing?
I add a comment node right before I display the date as the server sees it. Inside the comment node is the date/time of that post as the number of milliseconds since epoch. In Rails, for example:
<!--<%= post.created_at.to_i * 1000 %>-->
If they have JS enabled, I use jQuery to grab those nodes, get the value of the comment, then:
var date = new Date();
date.setTime(msFromEpoch);
// output date.toLocaleString()
If they don't have JS enabled, they can feel free to do the conversion in their head.
If you're trying to parse the ISO time, that may be the cause of your slowness. Also, how many dates are we talking?
Unfortunately, there is not.
HTML & CSS are strictly used for presentation, as such, there is no "smarts" built in to change the way things are displayed.
Your best bet would be to use a server side language (like .NET, Python, etc.) to emit the dates into the HTML in the format you want them shown to your user.
It is not possible to do this with HTML, it has no smart tags that can make any kind of decisions like this. It is strictly presentational. I do wonder, though, if HTML5 perhaps has a tag for something like this...
Anyways, the way I see it, you have 3 options:
Stick to the Javascript way. There's questions with more details on it on this website, such as How do I display a date/time in the user’s locale format and time offset? and How can I determine a web user’s time zone?
Try to use geolocation. That is, your server side script fires off a request to one of the many geolocator services out there on the user's first page visit to try and guess where the user is. The downside of this is that it will be wrong about 10% of the time, so it's not that much better than the market share Javascript is going to get you.... (all in all, then, not a very good method...)
Ask the user! You will see that most websites that want to display a tailored experience for you will ask you this sort of thing because it's just not possible to know. As a neat fallback, you could wrap the question around <noscript> tags so you only ask those with Javascript disabled while offering the Javascript experience to those that have it.
Dojo has some pretty good localizations for dates and currencies. Using this method also allows you to pick different formats (e.g.: short date vs long date) and force locales.
The language and the user's locale should be sent on the HTTP header. You can use those to create the correct date format server-side to be displayed to the user. However, this is often undesirable because many users completely ignore their locale settings in their OS and/or browser. So, you may be feeding USA style timestamps to New Zealanders.
I liked the trick posted in the comment above, but it sounds like a QA headache, since you could be dealing with a large number of clients that implement timestamps in very different ways.
The most effective solution I have seen, is to simple provide a panel to allow your users to choose what time format they like. Some users even ****gasp**** like ISO formats. Then you do the time format conversion server side. If your application language does not have good locale to timezone formatting mapping, check your database. Many databases provide locale-based customized timezone formatting as well.
Because this anwser still popups in google I share that this is now possible to do by using a readonly datetime-local input (see below) and you can then style the input the way you want:
<input type="datetime-local" value="2018-06-12T19:30" readonly />
For more information see: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local