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')
Related
This question already has answers here:
javascript: how to parse a date string
(4 answers)
Closed 5 years ago.
In javascript, while using exif-js to extract metadata of an image file, I am getting date time format as 2017:03:09 14:49:21.
The value in the DateTimeOriginal property is formatted as YYYY:MMY:DD HH:MM:SS. When I use var d = new Date(2017:03:09 14:49:21), it returns NaN. It's the colons in between the YYYY, MM, and DD which causes problem.
How to solve this problem?
Thanks in advance.
Don't use the built-in parser (i.e. Date constructor or Date.parse) for parsing strings as it's largely implementation dependent and unreliable. If you can trust the date to be valid, then the following will do:
/* Parse date string in YYYY-MM-DD hh:mm:ss format
** separator can be any non-digit character
** e.g. 2017:03:09 14:49:21
*/
function parseDate(s) {
var b = s.split(/\D/);
return new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5]);
}
console.log(parseDate('2017:03:09 14:49:21').toString());
It's fairly easy to add validation to the values. Otherwise, use a library and make sure you specify the format to parse.
My recommendation would be to use Moment (http://momentjs.com/docs/), as it provides clean parsing of dates. With Moment, what you want is this:
var tstamp = moment("2017:03:09 14:49:21", "YYYY:MM:DD HH:mm:ss");
var date = tstamp.toDate();
You can do simple string manipulation and create date if the format is always the same, as:
var str = "2017:03:09 14:49:21".split(" ");
//get date part and replace ':' with '-'
var dateStr = str[0].replace(/:/g, "-");
//concat the strings (date and time part)
var properDateStr = dateStr + " " + str[1];
//pass to Date
var date = new Date(properDateStr);
console.log(date);
This question already has answers here:
jquery/javascript convert date string to date
(6 answers)
Closed 6 years ago.
how can I convert a date string
'13.04.2015'
into JavaScript Date object in a performant way?
Try this parser:
var dateString = '13.04.2015';
var myDate = new Date(dateString.split('.').reverse());
Check the demo.
new Date( "13.04.2015".replace( /(\d{2}).(\d{2}).(\d{4})/, "$2/$1/$3") );
JSFiddle
Try this code:
var str = '13.04.2015',
dateParts = str.split('.'),
year = dateParts[2],
month = dateParts[1],
day = dateParts[0],
yourDate = new Date([year, month, day]);
JSFiddle example
Also if need to work a lot with dates, I would recomend you MomentJs Library
Code with it will look like:
moment('13.04.2015', 'DD.MM.YYYY')
JSFiddle example moment
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Extending JavaScript's Date.parse to allow for DD/MM/YYYY (non-US formatted dates)?
Convert dd-mm-yyyy string to date
Entered a date in textbox, for example: 05/09/1985, and I wanted to convert it to 05-Sep-1985 (dd-MMM-yyyy) format. How would I achieve this? Note that the source format may be dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format.
Code Snippet:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val());
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
This code returns 09-May-1985 but I want 05-Sep-1985. Thanks.
You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations
Then you can do things like:
var day = moment("12-25-1995", "MM-DD-YYYY");
or
var day = moment("25/12/1995", "DD/MM/YYYY");
then operate on the date
day.add('days', 7)
and to get the native javascript date
day.toDate();
Update
Below you've said:
Sorry, i can't predict date format before, it should be like dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format finally i wanted to convert all this format to dd-MMM-yyyy format.
That completely changes the question. It'll be much more complex if you can't control the format. There is nothing built into JavaScript that will let you specify a date format. Officially, the only date format supported by JavaScript is a simplified version of ISO-8601: yyyy-mm-dd, although in practice almost all browsers also support yyyy/mm/dd as well. But other than that, you have to write the code yourself or (and this makes much more sense) use a good library. I'd probably use a library like moment.js or DateJS (although DateJS hasn't been maintained in years).
Original answer:
If the format is always dd/mm/yyyy, then this is trivial:
var parts = str.split("/");
var dt = new Date(parseInt(parts[2], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[0], 10));
split splits a string on the given delimiter. Then we use parseInt to convert the strings into numbers, and we use the new Date constructor to build a Date from those parts: The third part will be the year, the second part the month, and the first part the day. Date uses zero-based month numbers, and so we have to subtract one from the month number.
Date.parse recognizes only specific formats, and you don't have the option of telling it what your input format is. In this case it thinks that the input is in the format mm/dd/yyyy, so the result is wrong.
To fix this, you need either to parse the input yourself (e.g. with String.split) and then manually construct a Date object, or use a more full-featured library such as datejs.
Example for manual parsing:
var input = $('#' + controlName).val();
var parts = str.split("/");
var d1 = new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
Example using date.js:
var input = $('#' + controlName).val();
var d1 = Date.parseExact(input, "d/M/yyyy");
Try this:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1') change day/month position.
See this http://blog.stevenlevithan.com/archives/date-time-format
you can do anything with date.
file : http://stevenlevithan.com/assets/misc/date.format.js
add this to your html code using script tag and to use you can use it as :
var now = new Date();
now.format("m/dd/yy");
// Returns, e.g., 6/09/07
I want to put the following string: '10-10-2013 03:04' in a Date object.
It's working in Chrome but Firefox tells me it's an invalid Date. (I guess they mean format?)
I tried to use Date.parse on it but that makes it a NaN.
What to do?
UPDATE:
I used the answer of thefourtheye, but now Chrome actually says it's an invalid date ..
var dateString = '10-10-2013 03:04';
dateString = dateString.replace(/-/g, ' ');
var DateToUse = new Date(dateString);
Returns an invalid date in Chrome.
<script>
var myDate = new Date("10 10 2013 03:04");
console.log(myDate);
</script>
According to the standard, https://www.rfc-editor.org/rfc/rfc2822#page-14, space can be used to separate date, month and year. The above example works perfectly in Chrome and Firefox.
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");