Change Date Format from millisecond - javascript

I have millisecond and i want to convert it in format Feb-01-2014 09:12:12. I have used following code
var today = new Date(1419359400000);
var p=today.toLocaleFormat('%b-%d-%Y %H:%M:%S');
But it is not working in chrome
Thanks

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleFormat reads:
Non-standard
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
Use some date library if you find yourself needing to formats a lot or use the native functions today.getYear(), today.getMonth() etc.
Keep in mind that toLocaleFormat uses the operating system locale which might not actually be what you want. Your dates might appear in a different language than the rest of your application.

Related

toLocaleTimeString() behaviour without arguments in Chrome and Safari

I read in the MDN documentation that:
toLocaleTimeString() without arguments depends on the
implementation,the default locale, and the default time zone
What does this mean exactly?
And I tried the following code in both Chrome(Version 87.0.4280.88) and Safari browser(Version 14.0).
new Date().toLocaleTimeString()
in Chrome it gives output as
16:57:37
whereas in Safari it gives output as
4:57:37 PM
With regards to the above example can someone explain how the implementation is changing from one browser to another, and why is it so?
Edit:
All this was done using MAC, I tried changing preferred language under Setting -> "Language and Region" to English(US) it was English(India) before, as soon as I did that change and restarted chrome the result became.
4:57:37 PM
But for Safari without doing this change it was able to show in 12 hour format, what was the reason for that?
The specification for toLocaleTimeString states:
This function returns a String value. The contents of the String are implementation-defined, but are intended to represent the “time” portion of the Date in the current time zone in a convenient, human-readable form that corresponds to the conventions of the host environment's current locale.
with the definition of implementation-defined being:
An implementation-defined facility is one that defers its definition
to an external source without further qualification. This
specification does not make any recommendations for particular
behaviours, and conforming implementations are free to choose any
behaviour within the constraints put forth by this specification.
Therefore browsers are free to implement this feature as they see fit.

Node 8 vs 11 Timezone is different

Running a simple new Date().toString(). On Node 11, You get something like
'Fri May 10 2019 10:44:44 GMT-0700 (Pacific Daylight Time)'
While on Node 8 you get
'Fri May 10 2019 10:44:44 GMT-0700 (PDT)'
Note the different in timezone abbreviation. Why is that? And how can you force toString() to always return the zone in the abbreviation?
Stolen answer from #ssube who was too lazy to log in and post.
the whole Intl object and default formats were introduced between those two versions, which may have become the new default for Date as well.
After some digging on my own, and reading some of the Intl spec:
The ECMAScript 2015 Internationalization API Specification identifies time zones using the Zone and Link names of the IANA Time Zone Database. Their canonical form is the corresponding Zone name in the casing used in the IANA Time Zone Database.
As to how to revert back to an abbreviated timezone, I am seeing that there are several github repos that suggest using regex, others using an abbreviation Map, or even Ben Nadel who uses some regex to process the short timezone or long timezone, as seen in his blog here
Looks like JavaScript leaves this up to the implementer. Based on the below GitHub Issue for ECMA262, there are known differences between the ways UNIX & Windows handle the timezone value.
Across multiple JS implementations, it seems that Date.prototype.toString writes the timezone (in parens) in a long, locale-dependent form on Windows, but in a short form (2-4 letters) from the tz database on Unix-based OSes. More details in the V8 bug tracker.
The spec is really light on details for Date.prototype.toString:
Return an implementation-dependent String value that represents tv as a date and time in the current time zone using a convenient, human-readable form.
Does anyone have a good memory of why this is the definition? Looks like it goes all the way back to ES1.
Fortunately, it seems that, at this point, implementations have converged on something that's almost always the same, with the exception of the timezone string.
For the timezone string, would it be a good idea to pick one of the two alternatives and standardize it across all platforms? Does anyone have evidence one way or the other whether either of the two is likely to be more web-compatible, or whether we need to preserve the variation?
Additionally, it looks like there is still active discussion in the V8 Issues for Date.prototype.toString() normalization.
Going through the NodeJS there doesn't seem to be an explicit mention of this in their change logs for v10+.
Update
After digging through V8 commits, it looks like there is a new Timezone Names Cache implemented for performance in V8 when using Date.prototype.toString(). Based on the below excerpt from the message for this commit, it seems like this change is why there is a difference between Node v8 & Node v11
To speed up Date.prototype.toString(), this patch adds a cache in the
DateCache for the string short name representing the time zone.
Because time zones in a particular location just have two short names
(for DST and standard time), and the DateCache already understands
whether a time is in DST or not, it is possible to keep the result of
OS::LocalTimezone around and select between the two based on whether
the time is DST or not.
In local microbenchmarks (calling Date.prototype.toString() in a
loop), I observed a 6-10% speedup with this patch. In the browser, the
speedup may be even greater as the system call needs to do some extra
work to break out of the sandbox. I don't think the microbenchmark is
extremely unrealistic; in any real program which calls
Date.prototype.toString() multiple times, the cache should hit almost
all of the time, as time zone changes are rare.
The proximate motivation for this patch was to enable ICU as a backend
for timezone information, which is drafted at
https://codereview.chromium.org/2724373002/ The ICU implementation of
OS::LocalTimezone is even slower than the system call one, but this
patch makes their performance indistinguishable on the microbenchmark.
In the tz database, many timezones actually do have a number of
different historical names. For example, America/Anchorage went
through a number of changes, from AST to AHST to YST to AKST. However,
both ICU and the Linux OS interfaces just report the modern timezone
name in tests for the appropriate timezone name, even for historical
times. I can see why this would be:
- For ICU, CLDR only has two short names in the data file: the one for dst and non-dst
- For Linux, the timezone names do seem to make it into the /etc/localtime file. However, glibc assumes there are only two
relevant names and selects between them, as you can see in its
implementation of localtime_r:
http://bazaar.launchpad.net/~vcs-imports/glibc/master/view/head:/time/tzset.c#L573
So, this cache should be valid until we switch to a more accurate
source of short timezone names.

Does momentjs have something similar to joda-time's localDate? If not, is it best to use .startOf?

In the joda-time library (and I assume Java 8's new time library), you can ignore times and time zones: https://www.joda.org/joda-time/apidocs/org/joda/time/LocalDate.html
I would prefer to avoid having times factor in in my small app. I just want the user to see their local date. Is there a momentjs equivalent to localdate? If not, would the best workaround be to use .startOf()? Thanks.
Edit: Just to be clear, this is not a formatting question.
"By default, moment parses and displays in local time.
If you want to parse or display a moment in UTC, you can use moment.utc()"
As explained here.
moment().format(); // 2013-02-04T10:35:24-08:00 (local date)
moment.utc().format(); // 2013-02-04T18:35:24+00:00 (UTC date)

Creating a time with a specific time and timezone in momentjs doesn't appear to work as per the doco

I am trying to set an arbitrary date/time in momentjs with a specific timezone such that the timezone is stamped on the object with the original hh:mm values.
From the doco at http://momentjs.com/timezone/docs/ - this is definitely possible.
However, from further testing (see http://jsfiddle.net/patsimon/SFf5V/2/), things don't quite work as they are document too.
From the doco:
moment.tz("2013-11-18 11:55", "America/Toronto").format(); // "2013-11-18T11:55:00-05:00"
From my running code:
moment.tz("2013-11-18 11:55", "America/Toronto").format(); // "2013-11-17T20:55:00-05:00"
This will obviously differ for others who run this from a timezone different to mine (+10:00) - but I was led to believe that the whole point of this method was to only honour the timezone explicitly provided?
This is a bug and has already been reported here:
https://github.com/moment/moment-timezone/issues/57

Internationalization(Number formatting "num.toLocaleString()") not working for chrome

i want do number formatting in Javascript.. and i use the following method
num.toLocaleString() which will work for Firefox, IE but doesnt work for Google Chrome..
Wat i need to add for it work in chrome browser.
The toLocaleString() method is by definition implementation-dependent: it uses the implementation locale, such as browser locale. So if I were looking at your page that uses the method, I would see numbers formatted according to Finnish or English locale, depending on which browser I’m using.
What you want is localization by the locale of the page, and for this you need something else. In simple cases you might code it yourself, but number formatting is in general complicated, making it reasonable to use a library, such as Globalize. Check out the compact source of a simple demo. In Globalize, you use standard language codes when specifying the locale.
Internationalization is always challenging and unfortunately there doesn't seem to be a consistent/pervasive solution to it. Your best bet is to use a 3rd party library to take care of things for you.
We rely heavily on googles closure library, which has some pretty powerful i18n (internationalization) tools. Take a look at http://www.daveoncode.com/2009/11/26/goog-i18n-numberformat-formatting-number-locale-string/ for an example of how to use it. In the end, it becomes as easy as:
// define italian number format symbols
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_it_IT;
// create new decimal formatter (PERCENT, CURRENCY, SCIENTIFIC are options)
formatter = new goog.i18n.NumberFormat(goog.i18n.NumberFormat.Format.DECIMAL);
// view formatted and localized string
alert(formatter.format(15650.579));
If you are new to closure, don't worry. It's not hard to get set up and has a multitude of excellent helper classes that you may find useful.
http://code.google.com/closure/library/docs/gettingstarted.html
The JavaScript internationalization support is quite poor (as you have discovered).
You might take a look at https://github.com/jquery/globalize
It handles number formatting, and also dates, times, currencies.
A bit of voodoo can implement your own number formatting. You could build this into String.prototype, but I didnt want that, since its localized.
function reverse(str) {
return str.split('').reverse().join('');
}
function num2str(num) {
var str = num+"";
// european
// return reverse(reverse(str.replace('.',',')).replace(/\d{3}/g,'$&.').replace(/\.$/,''));
// american
return reverse(reverse(str).replace(/\d{3}/g,'$&,').replace(/\,$/,''));
}
and then its
> console.log(25000.45)
> 25,000.45

Categories