This Script date.format.js in http://stevenlevithan.com/assets/misc/date.format.js
var txt = 04/04;<br/>
dateFormat(txt, “dd/mm/yyyy”);
result : 04/04/2001
I Want Result : 04/04/2013
You are feeding the function an ambiguous date, don't expect a neat result.
In Firefox, I get "01/01/1970", but if I wrap 04/04 in quotes, so I believe what you I get invalid date, check the js file in line 38 to see why.
What you can do is add the current year pro grammatically like this http://jsfiddle.net/nabil_kadimi/c3Nsf/2/:
var txt = '04/04';
txt += '/' + (new Date()).getFullYear();
window.alert(dateFormat(txt, "dd/mm/yyyy"));
You would want to read this wonderful article on date parsing idiosyncrasies between various browsers.
There are some rules of the thumb provided for working with dates and also about how Chrome is a more accepting browser than others in terms of date formats.
Related
I am trying to convert ISO time local time.
here is my code :
var local_date = new Date('2018-09-11T06:22:39.000-0400');
local_date.toLocaleDateString();
local_date.toLocaleTimeString();
this code is working fine in chrome but in IE its giving error.
first line of code gives me Invalid Date
Looking for a fix which works in all browsers.
FYI: I do not want to use moment.js or any other library, want it in vanilla javascript.
So, the problem is your date-string format.
By reading the Mozilla documentation about the Date Object we can see that your string has to follow the IETF-compliant RFC 2822 timestamps and the ISO8601.
If we open the second one (the ISO8601) we can see that the accepted format is YYYY-MM-DDTHH:mm:ss.sssZ where the Z may be (+|-)HH:mm.
So instead of new Date('2018-09-11T06:22:39.000-0400'); if we execute new Date('2018-09-11T06:22:39.000-04:00'); it works.
If you don't want to add it manually, you can do it automatically by using the splice method from this answer and the code:
// A nice Polyfill
if (!String.prototype.splice) {
String.prototype.splice = function(start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
}
// Your code
var dateString = '2018-09-11T06:22:39.000-0400'.splice(26, 0, ":");
var local_date = new Date(dateString);
local_date.toLocaleDateString();
local_date.toLocaleTimeString();
I don't claim that 2018-09-11T06:22:39.000-0400 is in an invalid format, but an unaccepted by the IE.
Also, if you want to vanilla javascript you should stop opening IE at all.
I have spent several hours trying to figure out how JavaScript works with dates. I have come across this question, but it does not seem to asnwer my specific question.
My input is a string like this:
"2018-02-19T07:00:00Z"
My goal is to transform this into a datetime which would differ from the original date by 4 hours - WITHOUT ANY TIMEZONE (!):
"2018-02-19T11:00:00Z"
Is it possible in JavaScript ?
Check out all the functions relating to "UTC" and "ISO" on the Date docs.
var input = "2018-02-19T07:00:00Z";
var t = new Date(input);
t.setUTCHours(t.getUTCHours()+4)
var iso = t.toISOString().replace(/\.\d+/,'');
console.log(iso);
(I added a little regex to get rid of the milliseconds so it matches your expected output, you can remove that if the miliseconds don't matter, it's valid ISO either way.)
It's 4 lines of code, you do not need a library.
In addition to #Occam'sRazor answer, you could also do it without using the Date object, by using some String manipulations :
var str = "2018-02-19T07:00:00Z";
var timeZoneHours = +str.split('-').pop().split(':')[0].split('T').pop() + 4;
console.log(timeZoneHours);
str = str.substring(0,str.indexOf(':') -2) + (timeZoneHours < 10 ? '0' + timeZoneHours.toString() : timeZoneHours.toString()) + str.substring(str.indexOf(':'), str.length);
console.log(str);
I have the following HTML:
<strong id="ut-open-date">27/06/2014</strong>
and I want to read the text/innerhtml and convert its format to "YYYY-MM-DD" so I can insert it into MySQL table. I am using the moment.js library and my code is below:
var CreateDate = moment(jQuery('#ut-open-date').html()).format("DD/MM/YYYY");
CreateDate = moment(CreateDate).format("YYYY-MM-DD");
But the code changes 27/06/2014 to 2016-06-03 and I cannot work out why.
I also tried this code with the same result.
var CreateDate = moment(jQuery('#ut-open-date').html()).format("YYYY-MM-DD");
Any help is appreciated.
If we break down your code step by step you can see where it is going wrong:
var CreateDate = moment(jQuery('#ut-open-date').html())
This part uses the default constructor to try to parse the date, this is unreliable at best and has been deprecated. So moment is trying to guess what the date format is here.
.format("DD/MM/YYYY");
This is taking what ever was read in step 1 and trying to turn it into a string with the format of DD/MM/YYYY
CreateDate = moment(CreateDate)
Now you are parsing again without specifying the format so moment is doing it's best to guess
.format("YYYY-MM-DD");
Now you have told it to turn whatever it guessed the date to be into a string with the format YYYY-MM-DD
Do this instead:
var CreateDate = moment(jQuery('#ut-open-date').html(), 'DD/MM/YYYY').format('YYYY-MM-DD');
The moment(dateString) form is deprecated you should use the form moment(dateString, expectedFormat) instead.
See moment documentation here: http://momentjs.com/docs/#/parsing/string-format/
Thanks to athms for link
The problem is you need to tell moment.js what format for date string you want parse by specifying second parameter. See all the supported format. If your format is not listed (See the Open Issue for NON-ISO strings), you need to specify the date format parameter.
moment( jQuery('#ut-open-date').html(), "DD/MM/YYYY" )
DEMO
I solved it by using split as follows:
var CreateDate = jQuery('#ut-open-date').text();
var DateArray = CreateDate.split('/');
CreateDate = DateArray[2] + '-' + DateArray[1] + '-' + DateArray[0];
I'm having trouble parsing a month year string into a date when using the jquery ui 's utility method $.datepicker.parseDate(format, string, settings). ( https://api.jqueryui.com/datepicker/ )
When I use it like
var dt = $.datepicker.parseDate('MM yy', 'January 2011');
I expect it to return a date which equals new Date(2011,00,1), but instead I get an invalid date. Does jqueryui's parseDate support full date string parsing? I can't really find any good docs on this. I expected it to support the full month parsing because the datepicker is able to display it in full month format. I've set up a fiddle* to demonstrate my problem. The core code from the fiddle is below.
*http://jsfiddle.net/mouseoctopus/fvrpG/
var text = $('#dateText').val();
var format = $('#dateFormat').val();
$('#instructions').text('Parse the date [' + text + '] using the format [' + format +']');
try{
var dt = $.datepicker.parseDate(format,text);
$('#result').text(dt);
}catch(exception){ }
So my question is.. it possible to parse a full month text using the parseDate?
I can't speak for jQuery parseDate, but you can use a native JavaScript Date.parse with the full month. The JavaScript function requires a full date though, so you'll need to add 1 in front of the date. It returns a timestamp which you can use it to create a new date.
You can find complete documentation at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Example
alert(new Date(Date.parse('1 January 2011')));
I have a date input field that allows the user to enter in a date and I need to validate this input (I already have server side validation), but the trick is that the format is locale dependent. I already have a system for translating the strptime format string to the the user's preference and I would like to use this same format for validating on the Javascript side.
Any ideas or links to a strptime() implementation in Javascript?
After a few days of googling I found this implementation which, although not complete, seems to handle all of the cases I have right now.
I've just added our php.js implementation of strptime(); I've tested it a bit, but it needs further unit testing. Anyhow, feel free to give it a shot; it should cover everything that PHP does (except for not yet supporting the undocumented %E... (alternative locale format) specifiers).
Note that it also depends on our implementation of setlocale() and array_map()...
https://github.com/kvz/phpjs/blob/master/functions/strings/setlocale.js
https://github.com/kvz/phpjs/blob/master/functions/array/array_map.js
Here is an example function that duplicates most of the functionality of strptime. The JavaScript date object generally will parse any date string you throw at it so you don't have to worry to much about that. So once you have a date object based off of your string you just push each element into a JS object and return it. This site has a good reference to the properties of the JavaScript date object: http://www.javascriptkit.com/jsref/date.shtml
function strptime(dateString){
var myDate = new Date(dateString);
return {tm_sec:myDate.getSeconds(),
tm_min: myDate.getMinutes(),
tm_hour: myDate.getHours(),
tm_mday: myDate.getDate(),
tm_mon: myDate.getMonth(),
tm_year: myDate.getFullYear().toString().substring(2),
tm_wday: myDate.getDay()};
}
var dateString = "October 12, 1988 13:14:00";
dateObj = strptime(dateString);
document.write("d:" + dateObj.tm_min + "/" + dateObj.tm_hour + "/" + dateObj.tm_mday + "/" + dateObj.tm_mon + "/" + dateObj.tm_year);