difference between date with and without time portion - javascript

let's say that I have two variables: one that contains a date string (without time) and another one that contains the same date string but with time 00:00:00 like this:
var date1 = '2013-10-23';
var date2 = '2013-10-23 00:00:00';
var date1_time = new Date(date1).getTime();
var date2_time = new Date(date2).getTime()
console.debug('Date 1 time: ' + date1_time + "\n" + 'Date 2 time: ' + date2_time);
The result in the console is this:
Date 1 time: 1382486400000
Date 2 time: 1382500800000
Why aren't these two equal to the same thing? Shouldn't date1's time portion default to 00:00:00 since I did not put a time?
Thank you

I just tested it on chrome and found out that
The first one gives you the timestamp for 00:00:00 UTC
The second gives you timestamp with your current timezone.
So if you substract them you will see +-your timezone:
var date1_time = new Date(date1).getTime();
var date2_time = new Date(date2).getTime();
console.log((date2_time-date1_time)/1000/60/60); //will print the timezone difference.

You can get exact what time the first variable is considering.
var timestamp = 1382486400000;
var date = new Date();
date = new date(timestamp + date.getTimezoneOffset() * 60000)
alert(date);
It all happens because of default UTC time zone and your current
timezone.

Related

moment.js timezone get milliseconds

I'm trying to get number of days passed. I'm storing epoch (milliseconds) for date.
I'm reading startDate from database (date value of first record) in milliseconds and I want to find current epoch in specified timezone.
I tried this:
var startDate = rows[0]['MIN_DATE'];
var endDate = moment().tz("America/New_York");
Then to calculate difference, I used:
var oneDay = 24 * 60 * 60 * 1000;
var daysCount = Math.ceil((endDate - startDate) / (oneDay));
The value of startDate is:
1522821600000 which is: Wednesday, April 4, 2018 2:00:00 AM GMT-04:00 DST
The value of endDate is:
Moment_d: Wed Apr 04 2018 22:24:45 GMT-0400 (EDT)_isAMomentObject: true_isUTC: true_isValid: true_locale: Locale_offset: -240_pf: Object_z: Zone__proto__: Object
The value of daysCount is 2, how?
How can I get milliseconds instead of object from:
moment().tz("America/New_York");
To directly answer your question, use .valueOf() to get the value of moment.tz("America/New_York")
var endDate = moment.tz("America/New_York").valueOf()
I'm having difficulty understanding your question, but I believe you're trying to get the difference between the days considering the correct timezone. The following gives an accurate result using .diff() (https://momentjs.com/docs/#/displaying/difference/)
var timeZone = "America/New_York"
var startDate = 1522821600000
var momentStartDate = moment.tz(startDate,timeZone)
var momentEndDate = moment.tz(timeZone)
alert(momentEndDate.diff(momentStartDate, 'days') );
Use fromNow() function. It is very straight-forward.
Do like this :
moment(date).fromNow();
It will give you number of days passed if date is past as well as number of days to go if date is future.
Below are is example:
var date = 1522821600000; // your date
console.log(moment(date).fromNow());
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Solved this with following statement:
var endDate = moment().tz("America/New_York").valueOf();

Return documents created since midnight

I want to find all document's created since midnight, regardless of the users timezone. If the users on Pacific time, it should show all their documents since midnight Pacific. Same with Eastern time.
I'm on Eastern time and this works for me:
var d = new Date();
var midnight = d.setHours(0,0,0,0); // last midnight
var count = Items.find({
username: Meteor.user().username,
createdAt: { $gt: midnight }
}).count();
But my client is on CST and it doesn't work for him. It instead shows documents created since like 10pm or 11pm CST the previous day. So this seems like a timezone issue for me.
Assuming that this is a client-side issue only (all of the times are stored in UTC on the server) then you can get the UTC adjusted time for midnight of the users current timezone by doing the following:
var now = new Date();
var midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var midnight_utc = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
See this fiddle: https://jsfiddle.net/Lbk1vo0j/1/
For example, for my current time zone (eastern) I get the following values for now, midnight, and midnight_utc (when printing the Date objects using the toLocaleString() method):
3/30/2015, 3:06:39 PM
3/30/2015, 12:00:00 AM
3/29/2015, 8:00:00 PM
try setUTCHours(0, 0, 0, 0);. It gets the Coordinated Universal Time that should be the same for every user.
I had similar requirement so I did used following method,
Created function to map datetime to _id
used that id to get my data.
Function that I am using is
function objectIdWithTimestamp(timestamp){
// Convert string date to Date object (otherwise assume timestamp is a date)
if (typeof(timestamp) == 'string') { timestamp = new Date(timestamp); }
// Convert date object to hex seconds since Unix epoch
var hexSeconds = Math.floor(timestamp/1000).toString(16);
// Create an ObjectId with that hex timestamp
var constructedObjectId = ObjectId(hexSeconds + "0000000000000000");
return constructedObjectId
}
using it
db.collection.find({_id:{$gte:objectIdWithTimestamp(Y/m/d H:i:s)}})
I will advice you try moment library and resolve the time zone problem. Where ever client code is getting executed, get its last midnight time, convert it to UTC time & then easily retrieve the information from MongoDb. Few moment library usage example, for more detail refer here
var str = "2013-12-01"
moment.tz(str, "America/Los_Angeles").format(); // 2013-06-01T00:00:00-07:00
moment.tz(str, "America/New_York").format(); // 2013-06-01T00:00:00-04:00
Minutes since midnight
You can get the minutes since midnight from the user's perspective. Try using it to query the server for changes since x minutes ago.
var d = new Date();
console.log(d);
var now = d.getTime();
d.setHours(0,0,0,0);
var midnight = d.getTime();
var minutes_ago = Math.floor((now-midnight) / (60 * 1000));
console.log(minutes_ago);
output:
Date {Thu Apr 02 2015 16:12:54 GMT-0700 (PDT)}
972
This should work:
var d = new Date();
var midnight = d.setUTCHours(0,0,0,0); // last midnight everywhere
var count = Items.find({
username: Meteor.user().username,
createdAt: { $gt: midnight }
}).count();

Error creating Date() in Javascript

I'm totally new to Javascript, and I'm getting trouble creating a Date from milliseconds.
I have this code:
function (result) {
alert("Retreived millis = " + result.created);
//Prints "Retrieved millis = 1362927649000"
var date = new Date(result.created);
alert("Created Date = " + date);
//Prints "Created Date = Invalid Date"
var current = new Date();
var currentDate = new Date(current.getTime());
alert("Current Date = " + currentDate);
//Prints "Current Date = Sun Apr 14 2013 12:56:51 GMT+0100"
}
The last alert proves that the creation of Date is working, but I don't understand why the first Date is not being created correctly, because the retrieved millis are correct... and as far as I understand in Javascript there're not datatypes, so it can't fail because the retrieved millis are a string or a long, right?
I suspect result.created is a string. Since the Date constructor accepts strings but expects them to be in a different format than that, it fails. (E.g., new Date("1362927649000") results in an invalid date, but new Date(1362927649000) gives us Sun Mar 10 2013 15:00:49 GMT+0000 (GMT).)
This should sort it (by converting to a number first, so the constructor knows it's dealing with milliseconds since The Epoch):
var date = new Date(parseInt(result.created, 10));

javascript - UTC date object manipulation

The UTC thing is really making me crazy... I am trying to have date and time on site in UTC so it has no affect of any timezone.
What I do, I create a date object
var d = new Date();
//convert it to utc
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
var utc_date = new Date(utc);
utc_date.setHours(20,0,0)
console.log(utc_date.getTime()) // I want this to be same irrespective of timezone, but don't know why it is changing
Please guide where I am doing wrong..?
UPDATED:
I wanted to create a dropdown of time like on http://jsfiddle.net/HNyj5/ the concept here is I use a timestamp either from client side of selected date or from db and then I generate this dropdown dynamically. So I want the timestamp to be similar on both server/client thats why I am trying to use UTC date object.
You can retrieve the UTC datetime from local time like this (example timezone = GMT+0100):
var currentUTC = new Date; //=>Mon Mar 18 2013 13:53:24
currentUTC.setMinutes(currentUTC.getMinutes()+currentUTC.getTimezoneOffset();
//=> currentUTC now: Mon Mar 18 2013 12:54:06
//or
var someUTC = new Date('1998/03/18 13:52'); //=> Wed Mar 18 1998 13:52:00
someUTC.setMinutes(currentUTC.getMinutes()+currentUTC.getTimezoneOffset();
//=> someUTC now: Wed Mar 18 1998 12:52:00
Or as a Date Extension with a one liner:
Date.prototype.UTCFromLocal = function(){
var a;
return new Date(Date.prototype.setMinutes
.call(a = this,a.getMinutes()+a.getTimezoneOffset()));
}
// usage (current date and time = Mon Mar 18 2013 14:08:14 GMT+0100
var d = new Date().UTCFromLocal(); //=> Mon Mar 18 2013 13:08:14
And to retrieve (from a UTC datetime) you could use:
Date.prototype.LocalFromUTC = function(){
var a;
return new Date(Date.prototype.setMinutes
.call(a = this,a.getMinutes()-a.getTimezoneOffset()));
}
Please guide where I am doing wrong..?
You are building a utc_date that is a completely different time, somehow biased by the getTimezoneOffset. Just do
var d = new Date();
d.getTime(); // milliseconds since epoch
or
Date.now();
And if you're working in UTC-land, you should use d.setUTCHours instead of the local-timezone-dependent setHours.
Actually what I was expecting the JS to do was if I pass the timestamp in the Date constructor it should make object w.r.t that timestamp but it converts it to localtimezone which was making issues for me.
So what I did for solving this problem I get the date object by passing the string of the selected date.
var date = new Date(selected_date_str); rather than passing the timestamp
as I was making dropdown of time with UTC timestamp as its value. The start hour:min of dropdown was dynamic, which I was passing as argument in the function, it was from_hr like if I want to create dropdown of time from 20:00 then I pass from_hr = 20
so now I set hour for the selected date
date.setHours(from_hr, 0, 0);
then I made a utc_time variable for making the the value for dropdown
var utc_time = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), from_hr, 0, 0, 0);
this will retain in all timezones, this is what I am going to use as the base. Then in the loop I was adding 15 mins in the time
var count = 0;
jQuery(elem).html('');
while(count <= 95){
var option = '<option value="{0}">{1}:{2}</option>'.format(utc_time/1000, ('0' + date.getHours()).slice(-2), ('0' + date.getMinutes()).slice(-2)); //here i used a format prototype, which you can find in the jsfiddle link of my question
jQuery(elem).append(option);
utc_time += 15 * 60 * 1000; //adding 15 mins in the utc timestamp
date.setMinutes(date.getMinutes() + 15)
count++; }
I was dividing the utc_time with 1000 to make it php compatible, because I was going to retrieve value from here and save in db.

jQuery: How to convert server time in UTC to web browser's local time?

I have a server time (east cost of USA) that I want to convert to user's local time regardless of his location. I don't know the user's time zone.
Here is a sample date stored in MongoDB (UTC time):
ISODate("2012-05-03T09:40:34.764Z") which becomes 5/3/2012 5:40:34 AM
I want to convert this to local time of the user.
Is there a plugin I can look at or someone has it done w/o plugin?
This my code which is not working:
var svrDate = new Date('5/3/2012 5:40:34 AM');
var tzo = ((new Date()).getTimezoneOffset() / 60) * (-1);
var userTime = new Date(svrDate.setHours(svrDate.getHours() + tzo)).toLocaleString());
Simple:
var d = new Date("2012-05-03T09:40:34.764Z");
alert(d);
In my case, this prints:
Thu May 03 2012 02:40:34 GMT-0700 (PDT)
Because I'm in California.
The Z at the end of the string indicates that the date string is in UTC. JavaScript already knows how to handle that. If you want local time, just call the usual getTime(), getMonth(), getDay() methods. If you want UTC time, call their UTC variants: getUTCTime(), getUTCMonth(), getUTCDay(), etc.
Have a look at the jquery-localtime plugin at https://github.com/GregDThomas/jquery-localtime - that will convert a UTC time to the local time.
`//Covert datetime by GMT offset
//If toUTC is true then return UTC time other wise return local time
function convertLocalDateToUTCDate(date, toUTC) {
date = new Date(date);
//Local time converted to UTC
console.log("Time :" + date);
var localOffset = date.getTimezoneOffset() * 60000;
var localTime = date.getTime();
if (toUTC)
{
date = localTime + localOffset;
}
else
{
date = localTime - localOffset;
}
date = new Date(date);
console.log("Converted time" + date);
return date;
}
`

Categories

Resources