Moment.js, get days in other locale - javascript

I'm using http://momentjs.com and i don't know how to change the locale.
For example :
var shortDay = moment(myDate).format('ddd');
This line return, depend of the days, Sun Mon ... Fri Sat. I want to return the same, but in french.
I tried var shortDay = moment(myDate).locale('fr').format('ddd'); but no effect. Any ideas ?

You need to load the relevant locale file
See http://momentjs.com/docs/#/i18n/loading-into-browser/
Then you just need to call moment().locale('fr') once and it will start using french.

Related

Javascript: how to convert a UTC date to local one?

Looks like a very simple thing to do? Not afrer reading this http://dygraphs.com/date-formats.html - what a mess!
var time_utc="2016-04-25 20:19:00.306671";
document.write("Local date:"+new Date(time_utc+" UTC")); // Firefox 44.0.2: Invalid Date
How do I print a date in above format adjusted to local time?
The article you provided mentions halfway through the page,
Using hyphens (-) instead of slashes (/) works in WebKit browsers, but
not in IE or FF. Beware the UTC parse of YYYY-MM-DD!
As well as,
Don't try to specify milliseconds. Only recent versions of Chrome will
understand you.
With the date 2016-04-25 20:19:00.306671 you use hyphens and milliseconds. You could modify your time_utc string a bit to make it compatible like so,
var time_utc = "2016-04-25 20:19:00.306671";
time_utc = time_utc.replace(/-/g, "/");
time_utc = time_utc.split(".").shift();
var d = new Date(time_utc);
d.toString();
The above code outputs,
Mon Apr 25 2016 20:19:00 GMT+0200 (CEST)
Have you looked into Moment.js? http://momentjs.com/ It's a handy date-object wrapper that makes date object manipulation easy. Particularly, the local() function provided will give you what you need here.
All you have to do is install moment from npm and then include it in your js file at the top like this:
var moment = require("moment");
Then to change your time_utc variable to local all you have to do is:
var time_utc="2016-04-25 20:19:00.307";
document.write("Local date:"+moment(time_utc).local());
As someone advised me before, it is not wise to include an entire library for a simple, one time function. As a disclaimer, my work requires me to do many date-time calculations and conversions throughout a large project, so including a library for ease is much preferred in my case. However, if you only have to use it this one time, my answer may not be the best.
If you use moment.js, you can use:
var time_utc = "2016-04-25 20:19:00.306671";
var localDate = moment.utc(time_utc).local();
You need append UTC to the string before converting it to a local date in js:
var date = new Date('25/04/2016 4:52:48 PM UTC');
date.toString() // "Mon Apr 25 2016 09:52:48 GMT-0700 (PDT)"

Getting timezone label in JavaScript

I know JavaScript Date objects contain getTimezoneOffset() for getting the offset, but is there any method that returns the label or name for that timezone?
For example, on my computer, in Chrome's console, if I do:
> new Date().toString();
Then I get:
< "Thu Feb 25 2016 08:49:56 GMT-0800 (Pacific Standard Time)"
What I'd like to do is take a Date and get back "Pacific Standard Time" portion for it.
Is this possible, and if so, how?
I dont think there is a reliable way without regex matching (see #nils answer). Not sure what caveats that date string comes with, so might be fragile? It looks like there are some libraries available that can simplify this
https://bitbucket.org/pellepim/jstimezonedetect/wiki/Home
var timezone = jstz.determine();
timezone.name();
"Europe/Berlin"
There's no straight forward way. You can get it through the following method.
Alternatively you can choose REGEX.
function getTimeZoneLabel(){
var str = new Date().toString();
return str.substring(str.indexOf("(")+1,str.indexOf(")"));
}
You could use a regular expression to get it:
var d = new Date().toString();
var timezone = d.match(/\(([^)]+)\)/)[1];
An approach would be to just get what's inside the paranteses. Juan Mendes posted a solution:
function getTimeZone() {
return /\((.*)\)/.exec(new Date().toString())[1];
}
getTimeZone();
Note that this is language, OS and browser specific (and therefor of course not the ideal solution).
If it is however okay for you to use a library, you could use jsTimezoneDetect.

How do I append the user's timezone to a string in Javascript?

I found some code here on Stack Overflow that does exactly what I want, which is to take a GMT time string and convert it to the local time on the user's browser. Awesome.
However, I'm stuck on what should be a very small thing. When I display the time, I want the user's current local timezone to display along with the time. The goal is to output a string that looks something like:
2014/02/19 15:12 (PST)
I've looked at the parameters for the Javascript Date() function, but, unless I'm blind, I don't see one that outputs the user's timezone. There's getTimezoneOffset(), which returns a number, but not the code for the timezone.
I've got all the rest of the time displaying fine, except for that last part where I want it to say PST (or GMT or JST or wherever the user is). Is there a way to do that?
It can be done creating a date and then performing some operations on it. If you take a look at format in which newly created Date object is created it is e.g. like:
Wed Feb 19 2014 07:29:26 GMT+0100 (Central European Standard Time)
Now you may simply take the whole name like:
var myDate = new Date();
var userTmzn = myDate.substring(myDate.lastIndexOf('(')+1).replace(')','').trim()
and this should give you this in userTmzn
Central European Standard Time
Now to make it neat and have an abbreviation you may try some more operations:
// Take the part with timezone name and strip it from trailing ')'
var fullName = myDate.split("(")[1].replace(")","");
// Split into words
var words = fullName.split(" ");
// Take just first letters
var timezoneCode = "";
for(i = 0; i < words.length; i++)
{
timezoneCode += words[i].charAt(0);
}
That should give you (following the same example) this in timezoneCode variable:
CEST
This is highly custom, not a ready solution. You should verify in the code that default date's toString() returns date in TIME FORMAT, you should test on various browsers, etc. This is just a clue.

Built-in function in Javascript to format date

I'm wondering if there is anything like this?
I'm getting my CMS to sort the content by date, so this is my approach.
First getting the current time.
var date = Date.now();
It will return me 1374426602321.
So now when I want to display that to the user and obviously we don't want to display the above, so I'm using this right now.
var formattedDate = new Date(date).toDateString(),
That will output
Sun Jul 21 2013
Which is good, but that is not really the correct or perfect way I guess.
I'm expecting more like Sunday July 21, 2013.
Is there a way that we can accomplish this by not using any of the plugin or any module and not having to create like another function to format this??
This is being done in the server-side using Node.js
use a library or a function... don't see any other way.
function getDateString(d){
return
["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][d.getDay()]+" "+
["January","February","March","April","May","June","July","August","September","October","November","December"][d.getMonth()]+" "+
d.getDate()+", "+
d.getFullYear();
}

javascript timezone format

I need to format a javascript Date to send via json to the server. The server expects the time to be in the format according to this example
2011-08-31T06:49:28.931 -0700
which it conveniently tells me when I try to submit something like
2011-08-31T06:49:28.931 -07:00
The trouble I am having is with the timezone part, -0700. I've been looking at the Date API, and don't see a way to specify the timezone format. I can do d.getTimezoneOffset, but it returns 240 (Im in EDT I think) for me.
So, I can convert 240 to 0400 to represent 4 hours. I am worried however about correctness for other timezones. My questions are
1) How to convert the result of the getTimezoneOffset() into the required format, and how to determine what the sign should be (thats the part I am worried about)?
2) Is there a way to get the format off the date object itself so I don't have to do anything custom? If i do d.toString() I get "Wed Aug 31 2011 09:48:27 GMT-0400 (EDT)", so here the timezone part is in the format I want. So it might be possible. Maybe the best solution is to just use a regex to grab the timezone off d.toString()...
3) Extra credit: is the format the server requires some sort of standard?
Update: using match(/^.*GMT(-?\d*)/) returns "-0400" at index 1 of the array. Perhaps I should just use that? Im wondering if that regex will work for all timezones in the context of the sign.
Try this code:
var d=new Date(Date.now()); // sets your date to variable d
function repeat(str,count) { // EXTENSION
return new Array(count+1).join(str);
};
function padLeft(str,length,char) { // EXTENSION
return length<=str.length ? str.substr(0,length) : repeat(String(char||" ").substr(0,1),length-str.length)+str;
};
var str=padLeft(String(d.getFullYear()),4,"0")+"-"+
padLeft(String(d.getMonth()),2,"0")+"-"+
padLeft(String(d.getDate()),2,"0")+"T"+
padLeft(String(d.getHours()),2,"0")+":"+
padLeft(String(d.getMinutes()),2,"0")+":"+
padLeft(String(d.getSeconds()),2,"0")+"."+
d.getMilliseconds();
//str+=" GMT";
var o=d.getTimezoneOffset(),s=o<0?"+":"-",h,m;
h=Math.floor(Math.abs(o)/60);
m=Math.abs(o)-h*60;
str+=" "+s+padLeft(String(h),2,"0")+padLeft(String(m),2,"0");
alert(str);
You might want to use one of the date/time formatting libraries that bakes in support for this timezone format (such as http://jacwright.com/projects/javascript/date_format/). In any case, you're right: there really is no good way to control the format output.
As far as the regex goes I don't know that all browsers consistently use the GMT string format, so that may not be the best path forward.

Categories

Resources