Date formatting in moment.js , weird date values - javascript

So I have 2 kinds of date coming from json.
m = '201811';
n = '/Date(1433030400000)/';
I am trying to use moment.js to format time, but I can not find appropriate methods for it I guess.
moment(m).format('YYYY DD') //"201811 01"
and the n value I can not understand it leads to this output :
moment(m).format('YYYY DD')//"2015 31"

When you pass a date to moment() constructor, you might have to specify in what format it is.
So for the first date you would need to do:
moment(m, 'YYYYMM').format('YYYY MM'); // if the date is indeed in the form YYYYMM
For the second date, just extract the numeric part from the string and feed it to moment:
var ts = n.match(/(\d+)/);
moment(+ts[1]).format('YYYY DD');
See the snippet:
var m = '201811';
var n = '/Date(1433030400000)/';
alert(moment(m, 'YYYYMM').format('YYYY MM'));
var ts = n.match(/(\d+)/);
moment(+ts[1]).format('YYYY DD');
alert(moment(+ts[1]).format('YYYY MM'));
<script src="http://momentjs.com/downloads/moment.js"></script>
EDIT:
thanks to #MattJohnson, if you have at least moment version 1.3.0, you can simply pass the string in the form /Date(1433030400000)/ to the moment() constructor, and it will automatically detect the proper format, see also here.

Just pass them to moment in the following format:
var m = '201811';
var n = '/Date(1433030400000)/';
var formattedM = window.moment(m, 'YYYYMM').format('YYYY MMM DD'); //2018 Nov 01
var formattedN = window.moment(n).format('YYYY MMM DD'); //2015 May 31
I've dropped an example into jsbin.
Thanks to Matt Johnson for pointing out that moment can take the /Date(1433030400000)/ format.

Related

Changing date format javascript

I'm pulling some data from two different APIs and I want to the objects later on.
However, I'm getting two different date formats: this format "1427457730" and this format "2015-04-10T09:12:22Z". How can I change the format of one of these so I have the same format to work with?
$.each(object, function(index) {
date = object[index].updated_at;
}
Here's one option:
var timestamp = 1427457730;
var date = new Date(timestamp * 1000); // wants milliseconds, not seconds
var dateString = date.toISOString().replace(/\.\d+Z/, 'Z'); // remove the ms
dateString will now be 2015-03-27T12:02:10Z.
Try moment.js
var timestamp = 1427457730;
var date = '2015-04-10T09:12:22Z';
var m1 = moment(timestamp);
var m2 = moment(date);
console.log(m1);
console.log(m2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
You can use .format() method in moment to parse the date to whatever format you want, just like:
m2.format('YYYY MMM DD ddd HH:mm:ss') // 2015 Apr 10 Fri 17:12:22
Check out the docs for more format tokens.
What you probably want in javascript, are date objects.
The first string is seconds since epoch, javascript needs milliseconds, so multiply it by 1000;
The second string is a valid ISO date, so if the string contains a hyphen just pass it into new Date.
var date = returned_date.indexOf('-') !== -1 ? returned_date : returned_date * 1000;
var date_object = new Date(date);
Making both types into date objects, you could even turn that into a handy function
function format_date(date) {
return new Date(date.indexOf('-') !== -1 ? date : date * 1000);
}
FIDDLE
Take a look at http://momentjs.com/. It is THE date/time formatting library for JavaScript - very simple to use, extremely flexible.

Reading the date from textbox as a string and converting it into as Date

I am reading the date from textbox by using javascript and trying to convert it as Date object.But my problem is date is converting as month and month is converting as date when converting the string to date.
Example:
03/12/2014 the value in the textbox
Actual Output:
03 as March,
12 as date (Its wrong)
Expected Output:
03 as date
12 as December (I am expecting)
While converting this string to date by using following snippet
var startTime = document.getElementById("meeting:startTime");
date.js
var stringToDate_startTime=new Date(Date.parse(startTime.value,"dd/mm/yy"));
moment.js
var date1=moment(startTime.value).format('DD-MM-YYYY');
In the above even i have used date.js and moment.js files also.But those also did not solve my problem.Please can anyone help me out to get rid out of this.
Try ...
var from = startTime.value.split("/");
var newDate = newDate(from[2], from[1] - 1, from[0]);
... assuming time included ...
var date_only = startTime.value.split("");
var from = date_only[0].split("/");
var newDate = newDate(from[2], from[1] - 1, from[0]);
I am not aware of an implementation of the Date.parse() method that accepts two arguments. You can view the Mozilla Date.parse() method description here Date.parse() - JavaScript | MDN.
It might be worth looking at the question/answer of this question for some more information: Why does Date.parse give incorrect results?
The next best option would be to split the date using String.split() and to rearrange the date parts
var dateStr = '03/12/2014 23:05';
var newDateStr = null;
var dateParts = dateStr.split('/');
if (dateParts.length == 3) {
var day = dateParts[0];
var month = dateParts[1];
var yearAndTime = dateParts[2];
// Rearrange the month and day and rejoin the date "12/03/2014 23:05"
newDateStr = [ month, day, yearAndTime].join('/');
} else {
throw new Error('Date not in the expected format.');
}
var date = new Date(newDateStr); // JS Engine will parse the string automagically
alert(date);
This isn't the most elegant solution, but hopefully that helps.

Timestamp conversion clarification

I created a jsfiddle here
e.onclick=timeConverter('2014-05-02 22:03:34'); //IF I PASS THIS STRING AS DATE, I GOT THIS: 2,May 2014 22:3:34
e.onclick=timeConverter('2014-05-02T22:03:34.890Z'); //IF I PASS THIS STRING AS DATE, I GOT THIS: 3,May 2014 6:3:34
Does "T" or "Z" in the string matters? If someone can enlighten me, thank you.
HTML:
<input type="button" id="format" value="Format Date">
Javascript:
function timeConverter(UNIX_timestamp){
var s = new Date(UNIX_timestamp).getTime()/1000;
var a = new Date(s*1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
var time = date+','+month+' '+year+' '+hour+':'+min+':'+sec ;
//var time = date+','+month+' '+year+' '+hour+':'+min+':'+sec ;
alert(time);
}
var e = document.getElementById('format');
e.onclick=timeConverter('2014-05-02 22:03:34');
//e.onclick=timeConverter('2014-05-02T22:03:34.890Z');
Check this document here which is a extract of ISO 8601.
'T' is just meant as separator between Time and Date.
'Z' is a special indicator for UTC (+00:00) as time zone
The Problem is, '2014-05-02 22:03:34' is kinda chrome specific formatting as far as i know, which treats this time as your local time. So the difference of exactly 8 hours appear.
So to be on the safe side, always remember to put the Separator in and keep in mind what timezone you are referring to.
see this wiki-article , the Z in your string means that you are using the
local timezone, so thats the reason for the differnce in your alert
According to ECMA-262, accepted datetime format is:
[+YY]YYYY[-MM[-DD]][THH:mm[:ss[.sss]]]Z
Where Z is either Z or + , - followed by HH:mm. If you specify Z at the end of your timestamp, it means the time is in UTC. Since you are living in GMT+8, your browser adds 8 hours to convert it to local time. Therefore, you get 3,May 2014 6:3:34 instead of 2,May 2014 22:3:34.

Converting UTC date to mm/dd/yyyy

I am having a date in isoUtc format and I want to convert it into mm/dd/yyyy format. I tried to use the hint given in this blog entry but the problem I am facing is that if I convert 2007-04-06T00:00Z it gives different dates when user time zone is different. I want that it should give 04/06/2007 always independent of the user timezone.
Any help is appreciated
var d = '2007-04-06T00:00Z';
var d2 = d.substring(5,7)+'/'+d.substring(8,10)+'/'+d.substring(0,4);
// outputs 04/06/2007
You could thy this, if you have always constant format:
var dateString = '2007-04-06T00:00Z',
dateRegExp = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/,
match = dateString.match(dateRegExp),
date;
if (match) {
date = new Date(match[1], match[2] - 1, match[3], match[4], match[5]);
console.log(date);
}
DEMO

how can change the text string to date object?

i am getting string from server and i need to covert that fetching string in to new date object.. for doing this, i tried this function, but no use, any one can help me to convert strings to date object?
my code is :
var nationZone = {
getNewYorkLocalTime : 'getTime.php?lat=40.71417&lan=74.00639',
getLondonLocalTime : 'getTime.php?lat=51.5&lan=0.1166667',
getChennaiLocalTime : 'getTime.php?lat=13.0833333&lan=80.2833333',
getBangaloreLocalTime:'getTime.php?lat=12.9833333&lan=77.5833333'
}
$.each(nationZone , function(key, value){
$.get(value, function(response){
var newdate = $(response).find('localtime').text();
if(key == "getNewYorkLocalTime"){
var newyourktime = new Date(newdate);
newyourktime.getTime()
}
});
});
but, the newyourktime is showing local time only.. any help please? as well i am getting the response from server is : 17 Nov 2011 18:09:47 - like this.
Use http://www.datejs.com/
As an example:
var newyourktime = Date.parse('2011-11-11, 11:11 AM');
alert(newyourktime.toString('dd/mm/yyyy HH:mm:ss EST'));
Check out the Datejs library documentation to meet your requirements, after your date string is parsed, you can do a lot with it.
This will try to parse the date using the client machine own local settings, which is not good.
Instead of passing it as string, pass it as the total seconds that passed since 1/1/1970 at midnight and use this number when constructing the new Date object of JavaScript.
For example pass this number: 1321614000000 and you will get November 18th 2011, 1 PM
You could use substr
day = newdate.substr(0,2);
month = newdate.substr(3,3);
year = newdate.substr(7,4);
var newyorktime = new Date(year, month, day);
Substr

Categories