converting json results to a proper date - javascript - javascript

Hi i am trying to convert a json date back to a normal dd/mm/yy date.
How can i convert the Customer.DateOfBirth dd/mm/yy from a json date back to a normal date?
Here my code?
// parse the date
var Birth = Customer.DateOfBirth;
if (Birth != '') {
// get the javascript date object
Birth = DateFromString(Birth, 'dd/MM/yyyy');
if (Birth == 'Invalid Date') {
Birth = null
}
else {
// get a json date
Birth = DateToString(Birth);
//REPLACE JSON DATE HERE WITH NORMAL DATE??
}
}
Any suggestion would be great.
Thanks

If you can change the JSON representation to yyyy/mm/dd then you can directly convert it using
Birth = new Date(Birth);
If you have to use the current format, then you have to do some manual parsing
Extract the day/month/year parts and create a string in the expected format
var parts = Birth.split('/'),
day = parts[0],
month = parts[1],
year = parts[2],// you need to find a way to add the "19" or "20" at the beginning of this since the year must be full for the parser.
fixedDate = year + '/' + month + '/' + day;
Birth = new Date(fixedDate);

You can create a Date object from mm/dd/yyyy string, so if your string is ordered dd/mm/yyyy you'll either get Invalid Date error, or, possibly worse, create a Date object with wrong date (Januray 10th instead of October 1st).
So you need to swap the dd and mm parts of your string before passing it to the Date constructor:
var datestr = Customer.DateOfBirth.replace(/(\d+)\/(\d+)\/(\d+)/,"$2/$1/$3");
Birth = new Date( datestr );
You could also pass a string in yyyy/mm/dd order:
var datestr = Customer.DateOfBirth.split('/').reverse().join('/');
Birth = new Date( datestr );

Related

How to get utc date from timestamp using javascript?

I have a variable containing timestamp ( in seconds generated with php ), I used following code to create date object using javascript
var newdate = new Date(arrivalDate);
then used following code to get formated date in utc
var tempdate = newdate.getUTCFullYear()+'-'+('0' + (newdate.getUTCMonth()+1)).slice(-2)+'-'+('0' + newdate.getUTCDate()).slice(-2);
It returns me a 1 day before date, not sure how to get utc date from a timestamp.
var newdate = new Date(arrivalDate);
newdate.toUTCString();

What the elegant way to convert date in string to Date object?

I have this date in string format:
"05/2016" or "12/2015"
How can I convert the dates above in string format to Date() javascript object?
Date constructor accepts params in next order: year, month, day, hours, minutes, seconds, milliseconds, so simply parse string and pass it into Date constructor.
var data = "05/2016".split('/');
// Add + before year to convert str into number. Decrease second param because month starts from 0..11.
var date = new Date(+data[1],data[0] - 1);
console.log(date);
Also, you can convert your string to format which would be parsed correctly by new Date ( See more about dateString in MDN Date.parse description.
// convert string "05/2016" -> "2016-05"
var dateString = "05/2016".split('/').reverse().join('-');
var date = new Date(dateString);
console.log(date);
The previous answers are not correct - they get either the month or the year wrong. This is right (see the comment by Frédéric Hamidi)
var str = "12/2015";
var arr = str.split('/');
var date = new Date(parseInt(arr[1], 10), parseInt(arr[0], 10)-1)
console.log(date)
You can split string to get an array then use Date constructor.
new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
var str = "12/2015";
var arr = str.split('/');
var date = new Date(parseInt(arr[1], 10), parseInt(arr[0], 10) - 1)
console.log(date)
You might want to look at Converting string to date in js
I had a similar issue and stumbled upon this existing link.

How do I pass the JSON date value from a textbox and convert it in Javascript?

I'm returning a date to a text box using JSON, this means my date is returned as a string like this:
/Date(1335205592410)
Can anyone tell me how I can access this date from my textbox and convert it to a useable date format i.e. DD/MM/YYYY There are many guides online but most of them suggest using substr(6), with my value being in a textbox I'm not sure how I'd use that approach. I access my textbox like so:
function dateChange() {
var date_box = document.getElementById('date').value;
...
... Code to populate textbox ...
...
}
The textbox is a generic html textbox, when the above function runs it populates it with the JSON date string.
<input id="date" name="date" />
I need help getting the date value from the textbox and then converting it to a useable date. Can anyone help me out?
Many thanks
Does this work ok?
var date = new Date(1335205592410);
var day = "0" + date.getDate();
var month = "0" + date.getMonth();
var year = date.getFullYear();
var formattedDate = day.substr(-2) + '/' + month.substr(-2) + '/' + year;
alert(formattedDate);
Microsoft .Net handles this date format, you can overcome by gettings the miliseconds inside de Date string.
implementation
var convertMSDate = (function() {
var pattern = /Date/,
replacer = /\D+/g;
return function(date) {
if (typeof date === "string" && pattern.test(date)) {
date = +date.replace(replacer, "");
date = new Date(date);
if (!date.valueOf()) {
throw new Error("Invalid Date: " + date);
}
}
return date;
}
}());
usage
var date = '/Date(1335205592410)';
console.log(convertMSDate(date));
// use ISO 8601 format
date = convertMSDate(date);
console.log(date.toISOString());
// get date parts
var year = date.getFullYear(),
month = date.getMonth() + 1,
day = date.getDate();
console.log([day, month, year].join('/'));

Convert date to other format in javascript

I am getting a date and a time from 2 input boxes with datebox plugin.
I have the date as "16-01-2015" and time as "11:37 AM". I need to send both to my server to add to the database but my database need the date in format: "2015-01-16 21:11:00"
How can I convert my both strings in a date or a string with the other format? I also need to convert 12 hour time to 24h time.
Using moment.js:
var dateInitial = "16-01-2015";
var timeInitial = "11:37 AM";
//Parse the date as String to Moment
var dateAsMoment = moment(dateInitial + " " + timeInitial, 'DD-MM-YYYY HH:mm A');
//Parse the date as Moment to String in the desired format
var dateToSend = dateAsMoment.format('YYYY-MM-DD HH:mm:ss')
http://jsfiddle.net/vcarvalho/w240pfz6/2/
// You can reverse the numbers in the date and adjust the hours as needed.
function parsedaytime(inputday, inputtime){
var dstr= inputday.value.split('-').reverse().join('-'),
tstr= inputtime.value.split(/:| /),
ampm= tstr.pop();
if(ampm== 'PM' && tstr[0]!== '12') tstr[0]-=-12;
return '"'+dstr+' '+tstr.join(':')+'"';
}
var inputday={value: "16-01-2015"},
inputtime={value: "11:37 PM"};
parsedaytime(inputday,inputtime)
returned value: (String)
"2015-01-16 23:37"

Convert string as 'mm/dd/yyyy' to 'day of week, month name, year' in javascript

I am getting Facebook users' friends birthday back from Facebook in the following format:
10/07/1967 or just the day and month as 10/07
I want to display it as "October, 07, 1967" or "October, 07"
Is there a way to convert this string into a date and format it in Javascript?
var MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var myDate, myFormatDate;
var date_str ='10/07/1967';
var t = date_str.split("/");
if(t[2]) {
myDate = new Date(t[2], t[0] - 1, t[1]);
myFormatDate = MONTHS[myDate.getMonth()] + "," + myDate.getDate() + "," + myDate.getFullYear();
} else {
myDate = new Date(new Date().getFullYear(), t[0] - 1, t[1]);
myFormatDate = MONTHS[myDate.getMonth()] + "," + mydate.getDate();
}
= RESULT:
= myDate -- the Date Object
= myFormatDate -- formated date string "October, 07, 1967"
Check out the awesome DateJS library. You'll be able to do what you want, and more ...
[No, i'm not involved in any way with DateJs, just a very satisfied user :-)]
To do it fast, without bells and whistles, you can first split your date
myDateParts = myDate.split("/");
Then build the new date from the parts:
myNewDate = new Date(myDateParts[2], myDateParts[1], myDateParts[0]);
Using moment.js you can convert a date with:
moment('10/07/1967', "MM/DD/YYYY").format("MMMM, DD, YY")
where the first part get a date from a string given a format ("MM/DD/YYYY"), then you just format the date as you wish giving another format ("MMMM, DD, YY")
If you don't want to use a framework, you could just pass in the string to the date constructor:
var birthday = new Date('10/07/1967');
The constructor will also accept strings without year, like '10/07'.
Then you can access each of the properties as you wish:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

Categories