parse string date to date object in javascript - javascript

I have a date in this format: '04-Aug-15'.
I want to be able to get a Date object in JS, I'm trying this:
var date = new Date(Date.parse('04-Aug-15', "MM/dd/yyyy"));
But I'm getting invalid date error message.
Any idea how can I fix this?

Just pass new Date the date string, and it'll turn it into a date.
var stringDate='04-Aug-15';
var date=new Date(stringDate);
console.log(date);

Try this to parse your date.
var date = new Date(Date.parse("04-Dec-15"));
You can then print your date by the following function.
window.alert( (date.getMonth() + 1) +
'/' + date.getDate() + '/' + date.getFullYear());

Related

jQuery invalid date error

Why is the first date invalid? I don't understand.
https://jsfiddle.net/r4dgjdn6/1/
$(document).ready(function() {
alert(new Date('19.12.2016 14:00'));
alert(new Date('12.12.2016 14:00'));
});
I want to calculate date difference but i keep getting the Invalid Date error.
You can use the library http://momentjs.com/ and use it like this:
var a = moment('19.12.2016 14:00', 'DD.MM.YYYY mm:ss');
var b = moment('12.12.2016 14:00', 'DD.MM.YYYY mm:ss');
//to calculate the diff
a.diff(b);
because the 'date' constructor can get specific "date format" as parameters
for example :
alert(new Date('Mon Dec 19 2016 14:00:00'));
take a look at this :
http://www.w3schools.com/js/js_dates.asp
EDIT:
if it is always in this format you can use this "quick" code to parse your string into the right format:
var inputString = '19.12.2016 14:00';
var tmpArray = inputString.split('.');
var result = tmpArray[1] + "-" + tmpArray[0] + "-" + tmpArray[2].split(' ')[0] + " " + tmpArray[2].split(' ')[1];
alert(new Date(result));

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('/'));

converting json results to a proper date - 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 );

Common FormatDate function for different date formats

Am formatting the Date Format in JavaScript with the below code
function changeDateFormat(date) {
var fromJSON = new Date(parseInt(date.replace(/(^.*\()|([+-].*$)/g, '')));
return fromJSON.getMonth() + 1 + "/" + fromJSON.getDate() + "/" + fromJSON.getFullYear() + " " + fromJSON.getHours() + ":" + fromJSON.getMinutes();
}
i have 2 scenarios where i call the function with 2 diferent parameters
if date = "/Date(1374145967638)/" am getting the correct o/p
if date = "7/18/2013 4:28:52 PM" am getting Jan 01 1970
Is there a way i can write a common function in javascript/Jquery to handle both the dates ?
Am looking for an option without any JQUERY Plugins.
Thanks
I think you can first create a javascript Date object from date string then format it in what ever way you want.
ex:
var date = new Date("7/18/2013 4:28:52 PM");
then you can use different date class methods and format the string manually.

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