setHour without change on Time Zone - node.js

I am coding a code on node.js which I need to set hour, minutes, seconds to now date without change time zone. (I get time from client which it sends time in hh:mm:ss format by UTC timezone)
My code on set time is:
var now = new Date();
console.log(now);
now.setHours(format.h);
now.setMinutes(format.m);
now.setSeconds(format.s);
the now time is:
2016-12-30T13:30:17.586Z
and format is:
13:29:29
when I set seconds, the result is
2016-12-30T18:29:29.345Z
It seems the time zone is changing; How can I set hour without timezone change?
UPDATE
I installed the momentjs and here is my code:
var now = moment();
console.log("before: " + now.format());
now.add(format.h, 'hours');
now.add(format.m, 'minutes');
now.add(format.s, 'seconds');
console.log("after: " + now.format());
here is logs:
format time= 3:45:38
before: 2017-01-06T12:55:45+03:30
after: 2017-01-06T16:41:23+03:30
Actually the time should be 2017-01-06T15:45:38+00:00

For any complex date/time manipulation it's better to use moment:
moment().set('hour', 13);
It will save you a lot of headaches.
See: http://momentjs.com/docs/

Instead of
date.setHours()
date.setMinutes()
date.setSeconds()
Use
date.setUTCHours()
date.setUTCMinutes()
date.setUTCSeconds()
And everything will work as expected :)

Related

Return new date after adding the number to the today's date in node js

I have a logical question may be it sound simple but I am facing problem while solving this. Situation is I have a number of days that is expire days now by using that number I have to create a expire date, let me give you one example.
if today's date is 25-07-2020 and no.of expire days is 10 then expire date should be 04-08-2020
I want to this to implement in node js, right now I am getting today's date using Date method.
const today = new Date().toISOString().replace(/\T.+/, '')
This returns today's date but now I am confused how can I get my expire date after adding no.of days.
You need to use setDate here
var currentDate = new Date();
currentDate.setDate(currentDate.getDate() + 10);
console.log(currentDate) //this will have the new date
You can do this with a function:
function addDays(date, days) {
const copy = new Date(Number(date))
copy.setDate(date.getDate() + days)
return copy
}
const date = new Date();
const newDate = addDays(date, 10);
So, you can't add 10 days by simple manipulation of the Date as a string, since you'd need to account for all sorts of edge cases (change of month, change of year, time-zone changes).
There are lots of good libraries out there that can help you, like date-fns or Moment.js.
However, if you want to do this without a library, it's quite straightforward:
const now = +new Date(); // Gets the date as ms since epoch
const expiry = new Date(now + (10 * 24 * 60 * 60 * 1000)); Adds 10 days worth of ms

momentJS: Getting wrong timestamp from date in a different timezone

There is one time input i.e. start_time
I am trying to get timestamp in milliseconds for these inputs
let start_time = "17:05:00";
var start_date_moment = moment(start_time, "HH:mm:ss");
console.log(start_timestamp);
output is -> moment("2019-04-24T17:05:00.000")
This output remains same on server and local
But when I am trying to get unix timestamp in milliseconds in the same way
var start_timestamp = moment(start_time, "HH:mm:ss").valueOf();
On server at different timezone
console.log(start_timestamp);//1556125500000
console.log(moment(start_timestamp/1000).format('YYYY-MM-DD HH:mm:ss'); //2019-04-24 17:05:00
On local
console.log(start_timestamp);//1556105700000
console.log(moment(start_timestamp/1000).format('YYYY-MM-DD HH:mm:ss'); //2019-04-24 22:35:00
This start_timestamp value is different on local and server. But timestamp shouldn't change with timezone, it should remains same for all timezones. Please help me with this.
How to get the correct and same value at both places. I got this link some what related to this https://github.com/moment/moment/issues/2035
There is no issue with dates any particular format, issue is only with timestamp.
You need to take the offset into consideration when using moment (using timezones moment.js). Since no offset was passed in the input, the moment will be based on the time zone of the computer the code is running on, hence the different values..
Example:
var a = moment.tz("2013-11-18 11:55", "Asia/Taipei");
var b = moment.tz("2013-11-18 11:55", "America/Toronto");
a.format(); // 2013-11-18T11:55:00+08:00
b.format(); // 2013-11-18T11:55:00-05:00
a.utc().format(); // 2013-11-18T03:55Z
b.utc().format(); // 2013-11-18T16:55Z
If you change the time zone of a moment object using moment-timezone only affects the value of the local time. It does not change the moment in time being represented, and therefore does not change the underlying timestamp.
A Unix Timestamp is always based on UTC - you can see it as the same timestamp at any given location in the world.
Official Moment Docs on timezones
Edit:
If you use utcOffset you should pass an integer:
Example:
moment.utc("2015-10-01 01:24:21").utcOffset("-240").format('YYYYMMDD HHmmss ZZ')
// "20151001 012421 +0000"
moment.utc("2015-10-01 01:24:21").utcOffset(-240).format('YYYYMMDD HHmmss ZZ')
// "20150930 212421 -0400"
MomentJS allows offset-arguments to be passed as string, but it expects the string to be in one of the ISO8601 formats: [+/-]HH:mm or [+/-]HHmm.
To avoid this all together you could, if known, pass the location as an argument like
moment.tz(start_time, "HH:mm:ss", "Asia/Kolkata").valueOf();
as mentioned in the first example above..

How to set timezone with moment?

i am using moment for getting server time .
moment.tz.setDefault("Asia/Kolkata");
var now = new Date();
var _p_date = moment.tz(now, zone).format();
time when inserting _p_date = 2016-01-05T18:32:00+05:30
But in database date variable is type of DATETIME. and time is saved as 2016-01-05 18:32:00.
and after that when i comparing with this to get time_ago funcionality. providing me wrong estimation.
using time ago = moment("2016-01-05T18:32:00.000Z").fromNow(); // is showing In 5 hours
Since your initial timezone is lost you have to create moment.tz object with selected timezone. Try this plunker
var date = moment.tz(moment("2016-01-05T18:32:00.000Z", "YYYY-MM-DDTHH:mm")
.format('YYYY-MM-DD HH:mm'), 'Asia/Kolkata');
console.log(date.fromNow());

Momentjs timezone - getting date at time in specific timezone

I am attempting to create a date from a UTC base in a user's specific timezone, in this case "America/Los Angeles" using momentjs/momentjs timezone. However, I'm not getting the results I expect:
var tempDate = moment(1448841600000); //moment("2015-11-30"); //monday 11/30 in UTC
var adjustedStart = moment.tz(tempDate, "America/Los_Angeles");
adjustedStart.hour(9);
adjustedStart.minute(30);
console.log("adjustedStart in milliseconds:" + adjustedStart.valueOf());
The console output is 1448875800000 which is 11/30/15 9:30AM in UTC/GMT, I was expecting 1448904600000 which is 11/30/15 9:30AM in Pacific Coast time. How can I translate this start date to the right time in the user's timezone?
Yes, 1448841600000 is the date you said:
moment(1448841600000).utc().format()
// "2015-11-30T00:00:00+00:00"
But that is a day earlier in Pacific time
moment(1448841600000).tz('America/Los_Angeles').format()
// "2015-11-29T16:00:00-08:00"
When you adjust it to 9:30 pacific, it's on the 29th, not the 30th.
moment(1448841600000).tz('America/Los_Angeles').hour(9).minute(30).format()
// "2015-11-29T09:30:00-08:00"
When you call valueOf, the result is:
moment(1448841600000).tz('America/Los_Angeles').hour(9).minute(30).valueOf()
// 1448818200000
This is the correct value, however it's different than the one you provided. However, it is indeed what I get when I run your code as well.
Screenshot from Chrome debug window, with your exact code:
Also, in comments you wrote:
//moment("2015-11-30"); //monday 11/30 in UTC
Actually, that would be in local time, not UTC. If you wanted UTC, you'd use:
moment.utc("2015-11-30")
Though it's unclear to me whether you are using this string input or the numeric timestamp.
If what you are asking is that you want the UTC date to be treated as if it were local and then have an arbitrary local time applied - that is a somewhat strange operation, but it would go something like this:
var tempDate = moment.utc(1448841600000);
var adjustedStart = moment.tz([tempDate.year(), tempDate.month(), tempDate.date(), 9, 30],
"America/Los_Angeles");
console.log("adjustedStart in milliseconds:" + adjustedStart.valueOf());
// adjustedStart in milliseconds:1448904600000
This gives the value you asked for, but to me - this is a smell that something is wrong with the expectation. I'd look a lot closer at the requirement and the other parts of the system.
From http://momentjs.com/docs/:
moment#valueOf simply outputs the number of milliseconds since the Unix Epoch
It is important to note that though the displays differ above, they are both the same moment in time.
var a = moment();
var b = moment.utc();
a.format(); // 2013-02-04T10:35:24-08:00
b.format(); // 2013-02-04T18:35:24+00:00
a.valueOf(); // 1360002924000
b.valueOf(); // 1360002924000
So it shouldn't differ for different timezones.
You should use adjustedStart.format(); to see the difference

Issue in timezone with Node.js Module 'time'

I just came across an issue that has happened today (due to being 31st of January here in Australia Sydney). Basically, given a year,date,hour,minute,second. I want to create a date as if I am in a timezone (Australia/Sydney) and then convert it to UTC (i.e. getting the milliseconds).
This is done due to the fact that the database (and the server) works in UTC, where as the client can be in any given timezone (when a post request is done, the client provides both the timezone and the year,month,date,hour,minute,second values)
The problem is, that when I am creating a date for today, its throwing off the date all the way back to January the 3rd of this month, here is the code that illustrates the problem
var scheduled, someTime, time, timeinfo, timezone;
process.env.TZ = 'UTC';
time = require('time');
timeinfo = {
hour: 14,
minute: '47',
year: 2013,
month: 1,
date: 31
};
timezone = 'Australia/Sydney';
someTime = new Date(timeinfo.year, timeinfo.month - 1, timeinfo.date, timeinfo.hour, timeinfo.minute, 1, 1);
scheduled = time.Date(timeinfo.year, timeinfo.month - 1, timeinfo.date, timeinfo.hour, timeinfo.minute, 1, 1, timezone);
console.log(someTime);
console.log(scheduled);
When you run this in Node.js, the time outputted by console.log(scheduled); is completely off.
Note: I am using the time npm library.
Seems to be a bug with how node-time calculates timezones, related to the order of the operations when doing the transform. There's an open issue (#28) on github.com as of now.
I have submitted a pull request, try that in the mean-time and see if it works for your particular case.
Please try the following codes
1.For GMT Time
var GMTtimeObj = new Date();
2.For UTC Time:
var UTCtimeObj = +new Date();
Let me know does it works for your requirement.
Go through this post's answers as well it might help you..
This was a bug that was fixed recently, please look at https://github.com/TooTallNate/node-time/pull/30
Its working perfectly now

Resources