How to format this JSON data to date(mm/dd/yyyy) - javascript

Sample JSON:
[{"DispatchDt":"2014-05-28T01:34:00","RcvdDt":"1988-12-26T00:00:00"}]
I have this set of dates and I want to convert it to the date format (mm/dd/yyyy). How do you do this is JavaScript?

Unfortunately parsing and formatting dates is a weak side of javascript.
So usually for that we use the 3rd party libraries like moment.js
An example of how you would do that with moment.js:
var date = '2014-05-28T01:34:00';
var parsedDate = moment(date);
var formattedDate = parsedDate.format('MM/DD/YYYY');
Demo: http://jsfiddle.net/8gzFW/

You may format the json string into new Date() then use js methods to get month,day,year or what exactly you need.
//format string to datetime
var DispatchDt = new Date(this.DispatchDt);
// then use this methods to fetch date,month, year needed
//getDate() // Returns the date
//getMonth() // Returns the month
//getFullYear() // Returns the year
var DispatchDt_date = DispatchDt.getDate();
var DispatchDt_month = DispatchDt.getMonth() + 1; //Months are zero based
var DispatchDt_year = DispatchDt.getFullYear();
Sample on jsFiddle

This would work
var a = "[{"DispatchDt":"2014-05-28T01:34:00","RcvdDt":"1988-12-26T00:00:00"}]";
var b = JSON.parse(c);
for (i in b[0]) {
b[0][i] = b[0][i].slice(0, 9)
}
console.log(b); // b now looks like this [ { DispatchDt: "2014-05-28", RcvDt: "1988-12-26" } ]
Please note the dates are stringified.

Related

How to convert 112889 (mmddyy) to 11/28/89 or 11/28/1989

How do we convert this unformatted date of 112889 (mmddyy) to specific format like 11/28/89?
console.log(new Date('112889'))
// I got this: Sat Jan 01 112889 00:00:00 GMT+0800
I have searched anywhere in google concerning this but found none specific answers.
Reference searches:
https://forums.asp.net/t/1987249.aspx?How+can+i+convert+Date+1365715800000+format+to+MM+dd+yyyy
Convert number into date using javascript
Im also thinking about momentjs formatting but couldn't find any doc about this or did i only missed it
Using the momentjs library you can specify what format your input string will come i.e. MMDDYY in this case.
var d = new moment("112889", "MMDDYY");
document.getElementById('dated').innerText = d.format('MM/DD/YYYY');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<div id="dated"></div>
Please have a look moment.js library. try this code
var date = moment('112889',"MMDDYY").format('MM/DD/YY');
console.log(data);
If you don't want to use a library and if you know that your input is always going to be of mmddyy format, you can do something like this:
var str = '112889';
var arr = str.match(/.{1,2}/g); // Splits string into 2 character chunks
var d = new Date(arr[2],arr[0],arr[1]);
console.log(d);
But this is quite not correct since if you give a string like 112804, JS (or anyone for that matter) will not know if it is 1904 or 2004 and it'll pick up 1904. In that case, you should specify explicitly:
var str = '112896';
var arr = str.match(/.{1,2}/g); // Splits string into 2 character chunks
var d = new Date(arr[2], arr[0], arr[1]); // new Date(yy,mm,dd);
var presentYear = Number((new Date()).getFullYear());
var dateYear = Number(d.getFullYear());
if (presentYear >= dateYear + 100) { // If adding 100 to year makes it greater than present year, then move to 2000s
d = new Date('20' + arr[2], arr[0], arr[1]);
}
console.log(d);

Time if statement not working

Hi I have a simple if statement which compares to dates, however its not running, I have tried debugging it but doesn't work.
dateFormat = "01/05/2099"
dateMissing = "25/11/2016"
if(dateFormat > dateMissing){
dateFormat = dateMissing;
}
You're comparing strings. That compares their characters, one by one from left-to-right, until it finds a difference, and then uses that difference as the result. Since "2" is > "0", that string is greater than the other.
You need to parse the dates and compare the result. Do not just use new Date(dateFormat) or similar, those strings are not in a format that is handled by JavaScript's Date object. Do the parsing yourself (directly, or via a library). E.g.
var dateFormat = "01/05/2099";
var dateMissing = "25/11/2016";
var parts, dt1, dt2;
var parts = dateFormat.split("/");
var dt1 = new Date(+parts[2], +parts[1] - 1, +parts[0]);
parts = dateMissing.split("/");
var dt2 = new Date(+parts[2], +parts[1] - 1, +parts[0]);
if (dt1 > dt2) {
dateFormat = dateMissing;
}
console.log("dateFormat:", dateFormat);
console.log("dt1", dt1.toString());
console.log("dt2", dt2.toString());
Your can't simply compare the strings containing dates. First, convert them to an acceptable format (milliseconds).
var dateFormat = new Date("05/01/2099").getTime();
var dateMissing = new Date("11/25/2016").getTime();
Then you can do your date comparision.

Parse dates from Javascript Date Object to regular datetime

How do I convert a date from JS Date Object to php datetime?
The following dates were converted to a Javascript Date Object from php datetimes:
"startsAt": "2015-08-15T10:46:00+00:00",
"endsAt": "2015-08-15T11:46:00+00:00"
converted using this syntax in javascript:
for (var i = 0; i < events.events.length; i++) {
events.events[i].startsAt = new Date(events.events[i].startsAt);
events.events[i].endsAt = new Date(events.events[i].endsAt);
}
startsAt and EndsAt looked like so after the conversion:
startsAt: Date 2015-08-15T11:46:00.000Z
endsAt: Date 2015-08-15T11:46:00.000Z
Now my goal is to do the opposite in javascript (angularjs): Convert from Javascript Date Object to php datetime 2015-08-15T10:46:00+00:00. Any idea would help. Thanks
Just to fix correct an answer below:
var rawDate = new Date();
var parsedDate = [
rawDate.getDate(),
(rawDate.getMonth() + 1), //because getMonth() starts from 0
rawDate.getFullYear()
].join('-');
console.log(parsedDate); // output could be: 19-08-2015 for example
or just call any of the following to convert date object to string:
rawDate.toJSON();
rawDate.toISOString();
You've got to parse it manually doing something like:
var rawDate = new Date();
var parsedDate = rawDate.getDate() + '-' + rawDate.getMonth() + '-' + rawDate.getFullYear();
console.log(parsedDate); // output could be: 19-08-2015 for example
Other possible ways of doing this could be found in here.

Javascript convert dates

I am getting this "20131218" date/time value from an API result.
What I want to do is convert this date into something like this "2013-12-18". I know this is very easy in PHP by simply doing this code:
echo date("Y-m-d",strtotime('20131218'));
output: 2013-12-18
This is what I tried in javascript:
var myDate = new Date("20131218");
console.log(myDate);
But the output is Date{ Invalid Date } so obviously this is wrong.
My question here what is the equivalent of strtotime in javascript? or if there's no equivalent, how would I convert this value as my expected result(2013-12-18) using javascript?
Your help will be greatly appreciated!
Thanks! :)
The value is invalid to convert it to date. So either from your PHP code send it as a proper format like 20131218
Or convert the value you get in your Javascript to similar kind of format.
var dateVal="20131218";
/*
// If it's number ******* //
var numdate=20131218;
var dateVal=numdate.toString();
*/
var year=dateVal.substring(0,4);
var mnth=dateVal.substring(4,6);
var day=dateVal.substring(6,8);
var dateString=year+"-"+mnth+"-"+day;
var actualDate = new Date(dateString);
alert(actualDate);
JSFIDDLE DEMO
Javascript has a Date.parse method but the string you have is not suitable to pass to it. You don't really need to create a date object just to format a string. Consider:
function formatDateStr(s) {
s = s.match(/\d\d/g);
return s[0] + s[1] + '-' + s[2] + '-' + s[3];
}
alert(formatDateStr('20131218')); // '2013-12-18'
If you wish to convert it to a date object, then:
function parseDateStr(s) {
s = s.match(/\d\d/g);
return new Date(s[0] + s[1], --s[2], s[3]);
}
The reason why it is showing Invalid date is, it wants it to be in format
Following format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS
If you breakdown your string using following format just add dash at relevant places then you are good to go and use newDate.
1. var myDate = new Date("2013-12-18");
alert(myDate);
2. var myDate = new Date(2013,12,18);
Eventually you can modify your string manipulate it and use it in aforementioned format.

Javascript to format date value

I am trying (and failing!) to format my date output using javascript, so I am asking for some help.
The date format is 2013-12-31 (yyyy-mm-dd), but I want to display the date as 12-2013 (mm-yyyy).
I have read many posts, but I am now just confused.
Here is the call to the javascript function:
changeDateFormat($('#id_award_grant_date').val()),
Here is the javascript function:
function changeDateFormat(value_x){
}
What you have is just a string, so just split it and put it back together in the wanted format
var date = '2013-12-31',
parts = date.split('-'),
new_date = parts[1]+'-'+parts[0];
FIDDLE
var d = '2013-12-31'
var yyyymmdd = d.split('-')
var mmyyyy = yyyymmdd[1]+'-'+yyyymmdd[0]; // "12-2013"
function changeDateFormat(str) {
var reg = /(\d+)-(\d+)-(\d+)/;
var match = str.match(reg);
return match[2] + "-" + match[1];
}
http://jsfiddle.net/wZrYD/
You can do this pretty easily with split and join.
var yyyymmdd = '2013-12-31'.split('-'),
mmyyyy = [ yyyymmdd[1], yyyymmdd[0] ].join('-');
console.log('The date is: ', mmyyyy );

Categories

Resources