javascript similar Date objects, return defferent epochs? - javascript

when i use different Date constructors i receive similar Date objects but when i get there epoch values they have slightly different values.
Is it a bug or something or i'm just passing wrong value formats into constructors?
> date1 = new Date();
Sun Oct 04 2015 15:31:33 GMT+0330 (IRST)
> date2 = new Date(date1.toString());
Sun Oct 04 2015 15:31:33 GMT+0330 (IRST)
> date3 = new Date(date1.toISOString());
Sun Oct 04 2015 15:31:33 GMT+0330 (IRST)
> date1.getTime();
1443960093117
> date2.getTime();
1443960093000
> date3.getTime();
1443960093117
I'm using node(v0.12.2) in Ubuntu 14.04.1.

Apparently date1.toString() does not take the milliseconds into account while date1.toISOString() does. Yes, this is not a bug, you're just passing different strings. For me:
var date1 = new Date();
console.log(date1.toString(), date1.toISOString())
// Sun Oct 04 2015 14:54:37 GMT+0200
// 2015-10-04T12:54:37.113Z

The ISO date format includes a field to represent a fractional part of a second. The default date format doesn't, and when a default date format is parsed the system assumes the second value is exact.
> new Date().toString()
'Sun Oct 04 2015 07:53:48 GMT-0500 (CDT)'
> new Date().toISOString()
'2015-10-04T12:53:58.769Z'
In the ISO string, .769 is the seconds fraction part.

When you just log a date it automatically uses the default method .toString() version which drops the milliseconds. Using the below code you can see that the .###Z is dropped for .toString() but not for .toISOString() because it is in the extended ISO format.
var date1 = new Date();
var date2 = new Date(date1.toString());
var date3 = new Date(date1.toISOString());
console.log('date1 ' + date1.toISOString());
console.log('date2 ' + date2.toISOString());
console.log('date3 ' + date3.toISOString());
console.log('date1 ' + date1.getTime());
console.log('date2 ' + date2.getTime());
console.log('date3 ' + date3.getTime());
Which returns
date1 2015-10-04T13:34:37.778Z
date2 2015-10-04T13:34:37.000Z
date3 2015-10-04T13:34:37.778Z
date1 1443965677778
date2 1443965677000
date3 1443965677778
Hopefully this helps.

Related

JS Date incrementation

Doing this without libraries.
dates.forEach((date) => {
if(date.getDay() == 6) {
console.log('sat', date)
var t = new Date()
console.log('sat new', new Date(t.setDate(date.getDate() + 1)))
} else ...
}
Gives this output
sat
Date Sat Jan 01 2022 00:00:00 GMT+0200 (Eastern European Standard Time)
sat new
Date Sat Apr 02 2022 19:10:27 GMT+0300 (Eastern European Summer Time)
The point of this code is to see if a date is a saturday. If so, increment it towards becoming a work day (i know it says +1 but its a wip)
The result is that the day gets incremented. However for some reason it moves the date towards being in march. I have looked around and apparently this is how you're supposed to do it, but its not doing it.
When I try console.log('sat new', t.setDate(date.getDate() + 1)) (without new Date()) I get a timestamp of 1646236273249. Which this site converts to the 16th of March. Don't know how useful this is.
I hope I gave all the important information here.
In order to increment a day to a given date:
date = new Date(date)
date.setDate(date.getDate() + 1)
console.log(date)
var t = new Date() - not passing anything to the Date constructor will make it "right now".
I think you need to pass the iterated date to the Date constructor:
dates.forEach((date) => {
if(date.getDay() == 6) {
console.log('sat', date)
var t = new Date(date) // this line
console.log('sat new', new Date(t.setDate(date.getDate() + 1)))
}
}

Node.js date.getDate() doesn't return the correct date after change date hours

I need to increment hours to a date, but I can't get the correct date after change the hours. For example:
Change the current date
let x = new Date(); // 2018-05-30T00:17:04.888Z
x.setHours(x.getHours() + 24); // 2018-05-31T00:17:04.888Z
Great! Now the date should be 2018-05-31, right?
But if I try to do the following:
x.getDate();
It still returns old date: 2018-05-30 and the same happens for x.getHours()
Is there a way to handle that?
It seems to work just fine.
var date = new Date()
date
>Wed May 30 2018 03:26:19 GMT+0000 (UTC)
date.setHours( (date.getHours() + 23) )
>1527726379425
date
>Thu May 31 2018 00:26:19 GMT+0000 (UTC)
date.getDate()
>31

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.

How to Convert Hard Coded date into standard GMT format

I need to convert a hard coded date into a standard GMT format.How can I do this?
The date I have is in the following format:
var myDate = 'dd|mm|yyyy';
There is no time or day description in the date.Just the 'dd|mm|yyyy' string.
Is there a way I can convert it into GMT?
Thanks in advance.
a = '22/02/2014'.split('/')
d = new Date(a[2],parseInt(a[1], 10) - 1,a[0])
//Sat Feb 22 2014 00:00:00 GMT+0530 (India Standard Time)
Now you have a javascript date object in d
utc = d.getUTCDate() + "/" + (d.getUTCMonth() + 1 ) + "/" + d.getUTCFullYear();
//"21/2/2014" for an accurate conversion to UTC time of day is a must.
If you are in say India, the Javascript Date object will have timeZoneOffset 330. So its not possible to keep a javascript Date object with timezone GMT unless your system time is GMT.
So if you want a Date object for calculation, you can create one with localTimezone and simply suppose it is GMT
pseudoGMT = new Date( Date.parse(d) + d.getTimezoneOffset() * 60 * 1000);
//Fri Feb 21 2014 18:30:00 GMT+0530 (India Standard Time)
If you can explain your high level requirement we might be able to help with some alternate solutions.
Use regex matching to extract the data you need:
var myDate = "21|01|2014";
var data = myDate.match(/(\d{2})\|(\d{2})\|(\d{4})/);
var date = new Date(data[3], data[2] - 1, data[1]);
Note that the month is 0-indexed, so january = 0
More on regular expressions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

Format date time JavaScript

How to format date and time like this in JavaScript ?
March 05, 2012 # 14:30 (UTC - 9:30)
I use this code to calculate EST time :
function getDate() {
var now = new Date();
var utc = now.getTime() + (now.getTimezoneOffset() * 60000);
return new Date(utc + (3600000 * -4));
}
I use the date-time-format that Tats recommended because doing it manually is a huge PIA.
var yourDate = dateFormat(getDate(), "mmmm dd, yyyy # HH:MM) + "(UTC -9:30)";
Keep in mind this isn't Daylight Savings aware.. and you are asking for UTC -9:30 in your format, but your function converts to -4. Also, I believe that now.getTime returns in UTC.. so you can just add your difference there.
JavaScript Date Format
Check out date.js! It's a really powerful little library for working with Dates in JavaScript.
To get today's date in EST, you can do something like...
var today = new Date();
today.toString(); // outputs "Wed Apr 11 2012 15:40:40 GMT-0500 (CDT)"
today.setTimezone("EST");
today.toString(); // outputs "Wed Apr 11 2012 14:40:40 GMT-0500 (CDT)"
Also, its worth mentioning to checkout moment.js. I think the two libraries complement each other.
If you do just
var now = new Date();
document.write(now);
you will get
Wed Mar 14 2012 20:53:06 GMT+0000 (GMT Standard Time)
Link1, Link2.
Is it what you want?

Categories