Javascript:String to date fails - javascript

I want to convert a date, given as yyyy-mm-ddThh:mm:ss to a Javascript Date.
First attemp:
var str = "2013-10-31T18:15:30";
var date = new Date(str)
Returns Thu Oct 31 2013 18:15:30 GMT+0100 (CET).
Second attemp:
var str = "2013-10-31T18:15:30";
var str_parts = str.split("T");
var date_parts = str_parts[0].split("-");
var time_parts = str_parts[1].split(":");
var date = new Date(date_parts[0], date_parts[1], date_parts[2], time_parts[0], time_parts[1], time_parts[2]);
Returns Sun Dec 01 2013 18:15:30 GMT+0100 (CET). Do I miss something? Shouldn't this also return Thu Oct 31 2013 18:15:30 GMT+0100 (CET)? Somehow, the date is incorrect, while the time fits.
The corresponding fiddle: http://jsfiddle.net/4CLAj/2/

In the Date constructor Date(year,month,day,hour,minute,second) the month is zero-based, i.e. January is zero.
So for the second attempt:
var date = new Date(date_parts[0], Number(date_parts[1]) - 1, date_parts[2], time_parts[0], time_parts[1], time_parts[2]);
See http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf section 15.9.1.4

Related

What type of date strings are these in JS?

I get a date string as Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time) from one place. I get it from 2021-09-17T11:50:59-04:00 in a second place.
I want to convert the first format to the second.
I am doing this in a crazy way, so I am thinking there must be a better one.
var d = new Date(`Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time)`);
var iso = d.toISOString();
var time = d.toTimeString();
console.log(iso);
console.log(time);
var [date] = iso.split('T')
var [,localTime, timezone] = time.match(/([^ ]+) GMT([^ ]+)/);
var timezoneWithColon = timezone.replace(/(-*[0-9]{2,2})([0-9]{2,2})/,"$1:$2")
var desiredFormat = '2021-09-17T11:50:59-04:00';
var convertedFormat = `${date}T${localTime}${timezoneWithColon}`;
console.log(desiredFormat)
console.log(convertedFormat)
console.log(desiredFormat === convertedFormat);
The fiddle is over at https://jsfiddle.net/Dave_Stein/8tLv2g4j/.
2021-09-17T11:50:59-04:00 is an ISO-8601 date string.
toISOString should work, however it will convert the time to UTC. If you want this to format in your current timezone, you'll have to use a library such as date-fns:
import { formatISO } from 'date-fns'
formatISO(new Date(`Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time)`))
// prints '2021-09-17T11:50:59-04:00'

JS UTC timestamp behaviour

I'm confused about how this time conversion works. I have timestamp 1462060800000 which when I turn in to date correctly becomes:
Sun May 01 2016 02:00:00 GMT+0200 (Central European Summer Time)
but then when I want to get the month with const startMonth = start.getUTCMonth() I get 4 instead of 5. Why is this happening and what do I need to do to get the correct month?
const timestamp = 1462060800000
const start = new Date(timestamp)
console.log(start) // Sun May 01 2016 02:00:00 GMT+0200 (Central European Summer Time)
const startYear = start.getUTCFullYear()
const startMonth = start.getUTCMonth()
console.log(startMonth) // 4
getUTCMonth() returns zero-based months. 4 is correct. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMonth.
I get it it's actually a month index that starts with 0.
The getUTCMonth() returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year).
From the docs see Date.prototype.getUTCMonth()
The getUTCMonth() method, like getMonth(), has a zero (0) count. This means that the period will be like this - 0 and 11. To get the desired month, you need to add +1:
const startMonth = start.getUTCMonth() + 1;
Loot it.
const timestamp = 1462060800000;
const start = new Date(timestamp);
console.log(start); // Sun May 01 2016 02:00:00 GMT+0200 (Central European Summer Time)
const startYear = start.getUTCFullYear();
const startMonth = start.getUTCMonth() + 1;
console.log(startMonth);

Wrong result when converting a date

I am just a beginner. My original date is: Friday, September 16th 2016, 09:00
And I need to convert it to this format: Fri Sep 16 2016 09:00:00 GMT+0000 (GMT)
But my code shows wrong date: Tue Sep 06 2016 09:00:00 GMT+0100 (BST)
Please see my code here:
var startdate = "Friday, September 16th 2016, 09:00";
var sdate = new Date(startdate.replace(/(\d)+(st|nd|th)/g, '$1'));
alert(new Date(sdate));
Can anybody help me with this issue? The example is here: https://jsfiddle.net/5hzwbbku/3/
By using momentjs I receive the strange results: https://jsfiddle.net/5hzwbbku/13/
Your regex is incorrect. /(\d)+(st|nd|th)/g matches the 16th but the captured group only contains 6. In order to return 16 your regex needs to be /(\d+)(st|nd|th)/g, like so:
var sdate = new Date(startdate.replace(/(\d+)(st|nd|th)/g, '$1'));
If you need the time to be in UTC, you'll have to append a timezone such as +0, +0000, or simply Z (for Zulu time).
var startdate = "Friday, September 16th 2016, 09:00";
startdate = startdate + ' +0000';
var sdate = new Date(startdate.replace(/(\d+)(st|nd|th)/g, '$1'));
alert(new Date(sdate));
On my system that returns Fri Sep 16 2016 11:00:00 GMT+0200 (CEST) which is 09:00 in UTC.
Other regexes that match correctly are /(\d)(st|nd|th)/g (note the complete absence of the +) and the one given by pastine in the comments /(.\d)+(st|nd|th)/g.

Remove time from GMT time format

I am getting a date that comes in GMT format, Fri, 18 Oct 2013 11:38:23 GMT. The problem is that the time is messing up the timeline that I am using.
How can I strip out everything except for the actual date?
If you want to keep using Date and not String you could do this:
var d=new Date(); //your date object
console.log(new Date(d.setHours(0,0,0,0)));
-PS, you don't need a new Date object, it's just an example in case you want to log it to the console.
http://www.w3schools.com/jsref/jsref_sethours.asp
Like this:
var dateString = 'Mon Jan 12 00:00:00 GMT 2015';
dateString = new Date(dateString).toUTCString();
dateString = dateString.split(' ').slice(0, 4).join(' ');
console.log(dateString);
I'm using this workaround :
// d being your current date with wrong times
new Date(d.getFullYear(), d.getMonth(), d.getDate())
You could use Moment.js, a library that provides many helper functions to validate, manipulate, display and format dates and times in JavaScript.
Using Moment.js lib:
var dateString = new Date('Mon Jan 12 00:00:00 GMT 2015');
moment(dateString).format('YYYY-MM-DD HH:mm');
Or simplified:
moment('Mon Jan 12 00:00:00 GMT 2015').format('YYYY-MM-DD HH:mm')
Well,
Here is my Solution
let dateString = 'Mon May 25 01:07:00 GMT 2020';
let dateObj = new Date(dateString);
console.log(dateObj.toDateString());
// outputs Mon May 25 2020
See its documentation on MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString
Just cut it with substring:
var str = 'Fri, 18 Oct 2013 11:38:23 GMT';
str = str.substring(0,tomorrow.toLocaleString().indexOf(':')-3);
In this case you can just manipulate your string without the use of a Date object.
var dateTime = 'Fri, 18 Oct 2013 11:38:23 GMT',
date = dateTime.split(' ', 4).join(' ');
document.body.appendChild(document.createTextNode(date));
You can first convert the date to String:
String dateString = String.valueOf(date);
Then apply substring to the String:
dateString.substring(4, 11) + dateString.substring(30);
You need to take care as converting date to String will actually change the date format as well.

Convert date to end of day

I get time in milliseconds from the server. I convert it to Date and get -
Mon Jul 22 2013 11:16:01 GMT+0200 (W. Europe Daylight Time) as the date in the record.
I want to separate out data of Monday, Tuesday etc into arrays. I am thinking of converting this date to Mon Jul 22 2013 23:59:59 GMT+0200 (W. Europe Daylight Time) and then filter out the records.
How can i change the date to the required end of the day time? or is there an easier way to do this ?
You could always construct a new DateTime object just using the year, month and day properties from the existing date, like so:
var actualDate = new Date(); // 2013-07-30 17:11:00
var endOfDayDate = new Date(actualDate.getFullYear()
,actualDate.getMonth()
,actualDate.getDate()
,23,59,59); // 2013-07-30 23:59:59
For future visitors, just use
var start = new Date();
var end = new Date();
start.setHours(0,0,0,0);
end.setHours(23,59,59,999);
Using http://momentjs.com:
var now = new Date().getTime();
var endOfDay = moment(now).endOf("day").toDate(); // Wed Jan 20 2016 23:59:59 GMT-0800 (PST)
var actualDate = new Date()
var eodDate = new Date(Math.floor(actualDate.getTime()/86400000+1)*86400000 + actualDate .getTimezoneOffset()*60000 - 1000)
where 86400000 are total milliseconds in a day
If two Date Objects are on the same day then they have the same Date String:
new Date('1374488161000').toDateString()
=> "Tue Jul 30 2013"
new Date('13744917610403').toDateString()
=> "Tue Jul 30 2013"
Although a rather naive method of comparing days, it's probably the simplest comparison.

Categories