Javascript datetime string to Date object - javascript

I am debugging a small application with some functionality which would only run in Chrome. The problem lies in a datepicker where you choose a date and time and the datepicker concaternates it into a datetime-string.
Anyway the string looks like this: 2012-10-20 00:00.
However, the javascript that uses it now just takes the string and initialize an object with it like this: new Date('2012-10-20 00:00');
This is resulting in an invalid date in Firefox, IE and probably all browsers but Chrome.
I need advise in how I best could transform this datestring to a Date object in javascript. I have jQuery enabled.
Thanks for your sage advise and better wisdom.

If the string format is always as you state, then split the string and use the bits, e.g.:
var s = '2012-10-20 00:00';
var bits = s.split(/\D/);
var date = new Date(bits[0], --bits[1], bits[2], bits[3], bits[4]);

It's just the simplify version:
var newDate = new Date('2015-04-07 01:00:00'.split(' ')[0]);

if str = '2012-10-20 00:00'
new Date(str.split(' ')[0].split('-').join(',') + ',' + str.split(' ')[1].
split('-').join(','))
should do the trick

use parseExact method
var date = new Date.parseExact(dateString, "yyyy-mm-dd hh-mm");

Related

Date format change To UTC

I have getting a dateformat like '23.10.2017'. I need to format this in to
'10/23/2017'
I just tried
var crDate='23.10.2017';
var newDateF=new Date(crdate).toUTCString();
but it showing InvalidDate
can anyone help to change the format.
Thanks in advance
I don't think using Date() is the solution. You can do
var crDate = '23.10.2017';
var newDateF = crDate.split(".");
var temp = newDateF[0];
newDateF[0] = newDateF[1];
newDateF[1] = temp;
newDateF.join("/");
This splits the string into an array, swaps the first and second elements, and then joins back on a slash.
A regex replacement will do the trick without any Date functions.
var date = '23.10.2017';
var regex = /([0-9]{2})\.([0-9]{2})\.([0-9]{4})/;
console.log(date.replace(regex,'$2/$1/$3'));
Just use moment.js if you can :
// convert a date from/to specific format
moment("23.10.2017", "DD.MM.YYYY").format('MM/DD/YYYY')
// get the current date in a specific format
moment().format('MM/DD/YYYY')
Moment is a very usefull and powerfull date/time library for Javascript.

Convert Date String(yymmdd) to Date Object in JS

I have a date string in "yymmdd" format i want to convert it into date object in JS
the input string is "161208"
I have tried code below
var mydate = new Date(InputDate);
but it says invalid date.
Here is the fiddle
https://jsfiddle.net/4ry0hL4t/
the basic need is that, I have a date string in "yymmdd" format and i have to convert it to different date formats like ("yyyy/mm/dd, yy-mm-dd","yy/mm").
Check my answer.
Basically you first need to give a proper format to your string. You can either do it manually or use moment.js.
stringFormat = moment(dateObject).format("YYYY-MM-DDTHH:mm:ss");
date = new Date(stringFormat);
This is also really helpful to understand how the different string formats are compatible with different browsers.
I'm not sure if this is what you're after?
var s = '161208';
var dt = new Date('20' + s.substring(0, 2) + '-' + s.substring(2, 4) + '-' + s.substring(4));

Error while converting date string to Date object in Firefox [duplicate]

This question already has answers here:
new Date() is working in Chrome but not Firefox
(14 answers)
Closed 8 years ago.
I am converting a simple dateString to Date object. The following code works perfectly on all browsers except Firefox.
var dateString = "02-24-2014 09:22:21 AM";
var dateObject = new Date(dateString);
console.log(dateObject.toDateString());
The Firebug console in Firefox says Invalid Date. What am I doing wrong here?
I also tried replacing - with \, but it didnt help.
Is it possible to do this without using any libraries?
Looks like Firefox does not like the - in dateString.
Replace all occurrences of - with / using a regular expression and then convert the string to Date object.
var str = '02-24-2014 09:22:21 AM';
str = str.replace(/-/g,'/'); // replaces all occurances of "-" with "/"
var dateObject = new Date(str);
alert(dateObject.toDateString());
Try: var dateString = "02/24/2014 09:22:21 AM"
dd-mm-yyyy is not a standard date format in EcmaScript. Some browsers implement it, some don't.
You tried replaceing hyphens with baskslashes, but you need to replace them with slashes.
if a date with hyphens comes from your server or something you can replace them using replace method and regex:
var dateString = "02-24-2014 09:22:21 AM";
dateString = dateString.replace(/-/g, '/');
Please try this:
var dateString = "02-24-2014 09:22:21 AM";
var dateObject = new Date();
dateObject.toDateString(dateString);
i will suggest you to use,
http://momentjs.com/
moment.js jQuery api.It works on all browers.
There are many ways to do same task. but easiest way is to add moment.js.
var dateString=moment('date as string').toDate();
http://jsfiddle.net/cTcNK/5/
I advise you to use the ISO8601 (http://en.wikipedia.org/wiki/ISO_8601) format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.
So: new Date('2014-02-24T09:22:21')
If the string is fixed... then split it and use Date constructor like
new Date('2014', '02' - 1, '24', '09', '22', '21')

How to get the date object

My value contains "08.07.1987", how to retrieve the date object for this string. new Date(val) gives correct date object values only for the string value that contains "/" format. can any one let me know hot to create date object for the values which contains "." or "-". in its format.
How about just adjusting the string to suit your needs?
var date1 = new Date("08.07.1987".replace('.','/'));
var date2 = new Date("08-07-1987".replace('-','/'));
You will need to be careful when asking Javascript to interpret a date in this format. As you can probably imagine, a date listed as "08.07.1987" doesn't really specify whether it's August 7th or July 8th.
In general, your best bet will be to specify a date format and parse accordingly.
you have to split the string into tokens for month date and year and then create it using JS Date API.
var date="08.07.1987";
var newDate = date.replace(/(\.|-)/g,"/"));
var dateObject = new Date(newDate);
Replace the delimiters?
var dateStr = "08.07.1987",
dateObj = new Date(dateStr.replace(/[-.]/g,"/"));
Of course you can encapsulate that in a function if need be...
try this new Date("08.07.1987".replace('.','/','g')); tested on firefox only

javascript : how to get 'utc date'

I have a date in this string format "02/28/2012" and I want to convert it to UTC.
I'm using the jquery datepicker to select thedate and populate an inputbox. any clues?
Thanks
var datestr = "07/08/2005";
var datearr = datestr.split("/")
var utc = Date.UTC(datearr[2],datearr[0],datearr[1]);
var utcdate = Date.UTC(2012,2,28);
The other answers are good, but they will give you the wrong result.
In Javascript, the month argument is zero-indexed, so make sure to subtract 1 from the standard month number,
var utcms = Date.UTC(2012,2-1,28);
Unfortunately jquery .datepicker.parseDate(str) injects a local timezone (it would be nice if the documentation said this), and Date(str) and Date.parse(str) appear unpredictable about their treatment of local vs UTC.

Categories

Resources