I have this string for example "November 8, 2016 - December 7, 2016" which I want to extract the two dates in the this format: YYYY-MM-DD.
Now, I managed to get the dates in the format I want in the following way:
HTML:
<span id="selecDate">November 8, 2016 - December 7, 2016</span>
Javascript:
date = $('#selecDate').text().split('-');
begin = new Date(date[1]);
begin = begin.toISOString().split('T')[0];
The problem is that date = ["November 8, 2016 ", " December 7, 2016"]
and begin = "Wed Dec 07 2016 00:00:00 GMT+0200 (IST)"
when in second line but in the last line the value of begin changes to "2016-12-06", one day earlier. Any idea how can I avoid it?
I'm working from (GMT+02:00) time zone
When you execute toISOString() the date you get back is in UTC time so it takes the time back 2 hours (because of your current timezone). Midnight on Dec 06 in IST is 22:00 in UTC time the day before.
If you wish to keep your timestamps in local time, you can use a .toLocaleDateString(), toLocaleString() or even just .toString() on your date object:
begin = new Date('December 7, 2016').toLocaleDateString();
Note that the date format is slightly different:
a.toLocaleDateString()
"12/7/2016"
a.toLocaleString()
"12/7/2016, 12:00:00 AM"
a.toString()
"Wed Dec 07 2016 00:00:00 GMT+0200 (IST)"
As MDN says in, method toISOString():
The timezone is always zero UTC offset.
And when you create your new Date('December 7, 2016'), what you get is:
Wed Dec 07 2016 00:00:00 GMT+0200
So in UTC, the hours are subtracted by 2, giving you the day before.
Solution:
begin = begin.getFullYear() + '-' + (begin.getMonth() + 1) + '-' + begin.getDate();
will result in: "2016-12-07".
date = ["November 8, 2016 ", " December 7, 2016"];
var b = new Date(date[1]);
//use these get methods to avoid all the confusion
var begin = b.getFullYear()+"-"+(b.getMonth()+1)+"-"+b.getDate();
console.log(_begin);
You should not parse strings with the Date constructor, especially when they are a format other than that specified in ECMA-262 as the behaviour is implementation dependent.
If you need Date objects, you should either use a library (e.g. moment.js, fecha.js) and provide the format to parse or write a simple function to parse the format to a date (see below).
However, if you just want a string in a different format, just reformat the string and avoid Dates altogether:
// Reformat a date string in format MMMM d, yyyy to yyyy-mm-dd
function reformatDate(s) {
var b = s.match(/\w+/g) || [];
var months = {jan:'01',feb:'02',mar:'03',apr:'04',may:'05',jun:'06',
jul:'07',aug:'08',sep:'09',oct:'10',nov:'11',dec:'12'};
return b.length == 3? b[2] + '-' +
months[b[0].toLowerCase().substr(0,3)] + '-' +
('0' + b[1]).slice(-2) : '';
}
console.log(reformatDate('November 8, 2016'))
The following functions parse a date in MMMM d, yyyy format to a Date object, then format it in yyyy-mm-dd format:
// Parse date string in format MMMM d, yyyy e.g. November 8, 2016
function parseDate(s) {
var months = 'jan feb mar apr may jun jul aug sep oct nov dec'.split(' ');
var b = s.match(/\w+/g) || [];
var m = months.indexOf(b[0].toLowerCase().substr(0,3));
var d = new Date(b[2], m, b[1]);
return d && d.getMonth() == m? d : new Date(NaN);
}
function toISODate(d) {
function z(n){return (n<10?'0':'')+n}
return d.getFullYear() + '-' + z(d.getMonth()+1) + '-' + z(d.getDate());
}
console.log(toISODate(parseDate('November 8, 2016')))
Using a library like moment.js you'd do:
'November 8, 2016 - December 7, 2016'.split(' - ').forEach(function(s) {
var d = moment(s,'MMMM D, YYYY').format('YYYY-MM-DD');
console.log(d);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>
Related
Say that I have DateTime in this format Fri Feb 02 2018 00:00:00 GMT+0530 (IST)
And from the time picker plugin getting the time 1:10am or 2:30pm in this format.
I am not sure how to calculate and combine/add them both to produce this result:
Fri Feb 02 2018 01:10:00 GMT+0530 (IST) or Fri Feb 02 2018 14:30:00 GMT+0530 (IST)
I wish if there was something to do as simple as this:
new Date(dateString).setHours(1:10am)
Seems like you need to parse it on your own:
function parseDaytime(time) {
let [hours, minutes] = time.substr(0, time.length -2).split(":").map(Number);
if (time.includes("pm") && hours !== 12) hours += 12;
return 1000/*ms*/ * 60/*s*/ * (hours * 60 + minutes);
}
To add it to a date:
new Date(
+new Date("Fri Feb 02 2018 00:00:00 GMT+0530")
+parseDaytime("1:20pm")
);
Here is a simple function to do what your after.
It basically splits the time using a regex, and then calls setHours & setMins, adding 12 hours if pm is selected.
The example below takes the current datetime, and sets 1:10am & 2:40pm..
function setHours(dt, h) {
var s = /(\d+):(\d+)(.+)/.exec(h);
dt.setHours(s[3] === "pm" ?
12 + parseInt(s[1], 10) :
parseInt(s[1], 10));
dt.setMinutes(parseInt(s[2],10));
}
var d = new Date();
console.log(d);
setHours(d, "1:10am");
console.log(d);
setHours(d, "2:40pm");
console.log(d);
You can parse the time string into hours & minutes, adjust the hours according to am/pm & set it to the date object then:
var dateString = 'Fri Feb 02 2018 00:00:00 GMT+0530 (IST)';
var hoursString = '2:30pm';
var parts = hoursString.replace(/am|pm/, '').split(':')
var hours = parseInt(parts[0]) + (hoursString.indexOf('pm') !== -1 ? 12 : 0);
var minutes = parts[1];
var date = new Date(dateString);
date.setUTCHours(hours, minutes);
console.log(date); // in your local time
console.log(date.toUTCString()); // in UTC (i.e. without timezone offset)
(Note setHours / setUTCHours mutates date object but returns unix timestamp of the updated datetime.)
In Javascript, I have date string as shown below:
var dateStr = "Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)";
I need to convert it to "YYYYMMDD" format. For example the above date should be : "20150325"
A good function for doing that which I found and used it always.
Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1; // getMonth() is zero-based
var dd = this.getDate();
return [this.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('');
};
var date = new Date();
date.yyyymmdd();
Here's a dirty hack to get you started. There are numerous ways of achieving the format you want. I went for string manipulation (which isn't the best performance).
var someDate = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");
var dateFormated = someDate.toISOString().substr(0,10).replace(/-/g,"");
alert(dateFormated);
function getFormattedDate(date) {
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return year + month + day;
}
And then just call the function :
alert(getFormattedDate(new Date());
The Date object is able to parse dates as string d = new Date( dateStr ); provided that they are properly formatted like the example in your question.
The Date object also offers methods to extract from the instance the year, month and day.
It's well documented and there are plenty of examples if you just Google for it.
What is worth mentioning is that the Date object doesn't handle timezone and the internal date-time is always converted into the client's timezone.
For example here's what I get if I try to parse your date in my browser (I'm in GMT+01):
dateStr = "Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)";
d = new Date( dateStr );
---> Wed Mar 25 2015 01:00:00 GMT+0100 (CET) = $2
If you need to handle timezone properly the easiest way is to use a library like MomentJS
Please advise:
Is there a way without regex or string replaces and so forth to convert a simple date such as:
Fri Jun 21 00:00:00 UTC+0100 2013
To a ISO8601 formatted date yy-mm-dd?
PS: 8601 date only, not date time.
Use moment.js http://momentjs.com/
moment(new Date(), "YYYY-MM-DD HH:mm Z");
or:
var date = moment("Fri Jun 21 00:00:00 UTC+0100 2013");
moment("Fri Jun 21 00:00:00 UTC+0100 2013", "YYYY-MM-DD HH:mm Z");
You can parse it and format it very easily whatever way you want http://momentjs.com/docs/ it is compatible with ISO-8601 dates for parsing as well.
Yes !
the date function in javascript.
var d = new Date("Fri Jun 21 00:00:00 UTC+0100 2013")
alert( d.getFullYear() + '-' + d.getUTCMonth() + '-' + d.getUTCDay())
2 lines of code :)
more info here : http://www.w3schools.com/jsref/jsref_obj_date.asp
Without regexes or string replaces? Yes, assuming that the format is fixed you could use .slice() and/or .substr() to extract the particular bits you need and rearrange them (unless such methods fall into your category of "and so forth"):
var input = "Fri Jun 21 00:00:00 UTC+0100 2013";
var year = input.slice(-4),
month = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'].indexOf(input.substr(4,3))+1,
day = input.substr(8,2);
var output = year + '-' + (month<10?'0':'') + month + '-' + day;
Or you could go ahead and get silly with a regex replace:
var output = input.replace(/^[^\s]+\s([^\s]+)\s(\d+)\s.*(\d{4})$/,function(m,p1,p2,p3) {
var month = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'].indexOf(p1)+1;
return p3 + '-' + (month<10?'0':'') + month + '-' + (p2.length===1?'0':'') + p2;
});
Of course you'd probably want to wrap such code in a reformatDate() method.
(For a "simple" reformatting of a date string, the Date object and its methods aren't particularly helpful unless the starting format is one recognised by Date.parse().)
Why dont you try to use the get functions, like getDate(), getMonth(), etc. For example:
var today = new Date();
var d1 = new Date();
alert(d1);
var date = d1.getDate();
var month = d1.getMonth() + 1;
var year = d1.getFullYear();
Then configure the string the way you want it to appear...!
I'm trying to compare two date strings for equality by wrapping them with the Date() object. I live in Seattle and for some reason, the second date string is converted to PST and then rendered in GMT, resulting in the below:
new Date("January 1, 2012")
>>> Sun Jan 01 2012 00:00:00 GMT-0800 (PST)
new Date("2012-01-01")
>>> Sat Dec 31 2011 16:00:00 GMT-0800 (PST)
Try the above in the chrome console and you should get the same results.
How do I get Date to evaluate the second statement as GMT instead of PST?
Do not use the Date object to parse date strings, it is specified as implementation dependent in ECMAScript ed 3 and doesn't work consistently across browsers. One format of ISO8601 date string is specified in ES5, but that doesn't work consistently either. Manually parse the string.
A couple of functions to convert to and from UTC ISO8601 strings:
if (!Date.prototype.toUTCISOString) {
Date.prototype.toUTCISOString = function() {
function addZ(n) {
return (n<10? '0' : '') + n;
}
function addZ2(n) {
return (n<10? '00' : n<100? '0' : '') + n;
}
return this.getUTCFullYear() + '-' +
addZ(this.getUTCMonth() + 1) + '-' +
addZ(this.getUTCDate()) + 'T' +
addZ(this.getUTCHours()) + ':' +
addZ(this.getUTCMinutes()) + ':' +
addZ(this.getUTCSeconds()) + '.' +
addZ2(this.getUTCMilliseconds()) + 'Z';
}
}
if (!Date.parseUTCISOString) {
Date.parseUTCISOString = function fromUTCISOString(s) {
var b = s.split(/[-T:\.Z]/i);
var n= new Date(Date.UTC(b[0],b[1]-1,b[2],b[3],b[4],b[5]));
return n;
}
}
var s = '2012-05-21T14:32:12Z'
var d = Date.parseUTCISOString(s);
alert('Original string: ' + s +
'\nEquivalent local time: ' + d +
'\nBack to UTC string: ' + d.toUTCISOString());
Taking robg's advice you might look at DateJS or moment.js
That's because of your time zone, you are 8:00 hours late to the "2012-01-01", so its showing like that, for me i got this
new Date("January 1, 2012")
Sun Jan 01 2012 00:00:00 GMT+0530 (IST)
new Date("2012-01-01")
Sun Jan 01 2012 05:30:00 GMT+0530 (IST)
I'm using a script calendar that when I choose a date, it convert it to a new format (yyyy-mm-dd)
It works in most browser but in Firefox and Opera, I get an invalid date format because the format i work with is RFC 822.
I'm looking for a way to convert this date format
example:
Thu Sep 08 2011 12:00:00 GMT-0400 (EDT)
and change it to
2011-09-08
Could that be done in javascript ?
UPDATE
Here's my code trying to replace the (EDT) to nothing
$(".taskDate").datepick({
onSelect: function(selectedDate){
selectedDate = selectedDate.replace(/ \(.+\)/, '');
//alert(selectedDate);
var newDate = new Date(selectedDate);
$(".selectedDate").text(newDate.getFullYear()+'-'+(newDate.getMonth()+1)+'-'+newDate.getDate());
location.href="index.php?date="+newDate.getFullYear()+'-'+(newDate.getMonth()+1)+'-'+newDate.getDate();
}
});
Now I get an error
selectedDate.replace is not a function
How come ?
UPDATE 2
Fixed it because it seems that it was an object and not a darn string.
Added
selectedDate = selectedDate.toString();
before the new Date();
Now it's working for all browsers...
Works in Firefox6, see my jsfiddle.
var sOriginalDate = 'Thu Sep 08 2011 12:00:00 GMT-0400 (EDT)';
var oDate = new Date(sOriginalDate);
var iMonth = oDate.getMonth() + 1;
var iDay = oDate.getDate();
var sNewDate = oDate.getFullYear() + '-'
+ (iMonth < 10 ? '0' : '') + iMonth + '-'
+ (iDay < 10 ? '0' : '') + iDay;
alert(sNewDate);
Since the date is RFC 822 you could parse it to a valid Date (the ending EDT does not affect the result):
var dateAsDateObject = new Date(Date.parse(dateInRFC822Format));
This will work with dateInRFC822Format equal to either "Thu Sep 08 2011 12:00:00 GMT-0400 (EDT)" or "Thu Sep 08 2011 12:00:00 GMT-0400"
Now you can get the info you require from dateAsDateObject:
year: dateAsDateObject.getFullYear()
month: dateAsDateObject.getMonth()
day: dateAsDateObject.getDay()
Note: for formatting, if you don't mind using jqueryui you could also use the $.datepicker.formatDate() method. E.g. var stringRepresentation = $.datepicker.formatDate('yy-mm-dd', dateAsDateObject);
Try:
var mydate = new Date(originaldate);
mydate = mydate.getYear() + '-' + (mydate.getMonth() + 1) + '-' + mydate.getDate();