[英]date manipulation in javascript
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 . 我有此字符串,例如
"November 8, 2016 - December 7, 2016"
,我想以以下格式提取两个日期: YYYY-MM-DD 。 Now, I managed to get the dates in the format I want in the following way: 现在,我设法通过以下方式以所需的格式获取日期:
HTML: HTML:
<span id="selecDate">November 8, 2016 - December 7, 2016</span>
Javascript: 使用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"]
问题在于
date = ["November 8, 2016 ", " December 7, 2016"]
and begin = "Wed Dec 07 2016 00:00:00 GMT+0200 (IST)"
并
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. 在第二行但在最后一行时,begin的值将提前一天更改为
"2016-12-06"
。 Any idea how can I avoid it? 知道如何避免吗?
I'm working from (GMT+02:00) time zone 我正在(GMT + 02:00)时区工作
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). 当执行
toISOString()
,您返回的日期是以UTC时间表示的,因此要花费2个小时的时间(因为当前时区)。 Midnight on Dec 06 in IST is 22:00 in UTC time the day before. IST的12月6日午夜是前一天的UTC时间22:00。
If you wish to keep your timestamps in local time, you can use a .toLocaleDateString()
, toLocaleString()
or even just .toString()
on your date object: 如果希望将时间戳记为本地时间,则可以在日期对象上使用
.toLocaleDateString()
, toLocaleString()
或什至只是.toString()
:
begin = new Date('December 7, 2016').toLocaleDateString();
Note that the date format is slightly different: 请注意,日期格式略有不同:
a.toLocaleDateString()
"12/7/2016"
a.toLocaleDateString()
"12/7/2016"
12/7/2016"12/7/2016"
a.toLocaleString()
"12/7/2016, 12:00:00 AM"
a.toLocaleString()
"12/7/2016, 12:00:00 AM"
2016,12:"12/7/2016, 12:00:00 AM"
a.toString()
"Wed Dec 07 2016 00:00:00 GMT+0200 (IST)"
a.toString()
"Wed Dec 07 2016 00:00:00 GMT+0200 (IST)"
As MDN says in, method toISOString()
: 就像MDN所说的
toISOString()
方法:
The timezone is always zero UTC offset.
时区始终为零UTC偏移。
And when you create your new Date('December 7, 2016')
, what you get is: 当您创建
new Date('December 7, 2016')
,您将获得:
Wed Dec 07 2016 00:00:00 GMT+0200 2016年12月7日星期三00:00:00 GMT + 0200
So in UTC, the hours are subtracted by 2, giving you the day before. 因此,在UTC中,小时数将减去2,从而得到前一天的信息。
Solution : 解决方案 :
begin = begin.getFullYear() + '-' + (begin.getMonth() + 1) + '-' + begin.getDate();
will result in: "2016-12-07". 结果为:“ 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. 您不应该使用Date构造函数来解析字符串,尤其是当它们的格式不同于ECMA-262中指定的格式时,因为行为取决于实现。
If you need Date objects, you should either use a library (eg moment.js , fecha.js ) and provide the format to parse or write a simple function to parse the format to a date (see below). 如果需要Date对象,则应该使用一个库(例如moment.js , fecha.js )并提供解析格式,或者编写一个简单函数将格式解析为日期(请参见下文)。
However, if you just want a string in a different format, just reformat the string and avoid Dates altogether: 但是,如果您只想使用其他格式的字符串,则只需重新格式化该字符串并完全避免使用Dates:
// 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: 以下函数将MMMM d,yyyy格式的日期解析为Date对象,然后将其格式化为yyyy-mm-dd格式:
// Parse date string in format MMMM d, yyyy eg 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: 使用像moment.js这样的库,您可以执行以下操作:
'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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.