How to set timezone with moment? - node.js

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());

Related

Convert user define time to UTC using moment

We have application where we ask user to define time when they want to publish some content. In our application, user will select that content should publish X(0-5) day before target date and y time (0-23).
So if user create a content with publish date = "09/21/2021" and publish time as 3 it means this content needs to publish at 3 AM on 09/21/2021.
In our Mongo DB we need to store the calculated date as "2021-09-21T07:00:00" So it can be pulled by our Cron Job.
We tried will following without any success
var promotedDate = "2021-08-19 04:00:00"
var fmt = "YYYY-MM-DD hh:mm:ss";
var m = moment.utc(promotedDate, fmt);
console.log('promoted date ', tempDate)
console.log(m.local().format(fmt));
console.log(m.utc().format(fmt));
But it gives 2021-08-19 12:00:00
Any help ?
You can use moment.toISOString(). That will give you UTC regardless of the timezone of the moment in question thus: 2013-02-04T22:44:30.652Z.
Since that comes with milliseconds and a Z for Zulu time, we need to strip off the last 5 characters with string.slice():
const promotedDate = "2021-08-19 04:00:00";
const m = moment.utc(promotedDate, "YYYY-MM-DD hh:mm:ss");
const iso8601 = m.toISOString()
.slice(0,-5); // removes milliseconds and `Z` for Zulu
console.log( `promoted: ${promotedDate}` );
console.log( `iso8601: ${iso8601} );

Error message "cannot find function getFullYear(...)" when entering date and trying to save the record

We are trying in a RESTLet to access the sublist "demandplandetail" from a NetSuite Item Demand Plan. Everything goes fine until a certain point. We are able to load it and process the demandplan for 2020. However, here it gets frustrating.
We know (can see from NetSuite) that there is data also for 2021. However, to access that from SuiteScript seems very difficult.
1st solution) The item demand plan has the field "year". OK, just set that to 2021, save and reload the record. Result: saving ignored, year still is 2020.
2nd solution) Set the year using a Date object as in:
var demandPlan = record.load(...)
var d = new Date();
demandPlan.setValue({
fieldId: 'year',
value: d
});
Gives the following:
:"TypeError: Cannot find function getFullYear in object NaN. (NLRecordScripting.scriptInit$lib#59)","stack":["setDatesForMonthAndYear(NLRecordScripting.scriptInit:108)","anonymous(N/serverRecordService)"
on saving the record. I also get the same using (various) strings adhering to acceptable date formats (as in '1/1/2021'). I have also tried the format package giving me a date string -> the same result.
Also read somewhere that you may need to set the start date (field 'startdate') in the record. Tried several variations but it stubbornly refuses :(.
Wonder if anyone has seen anything similar?
Best Regards,
Toni
Hi Please try the below code also check if you're passing date object to the field not the date string.
function formatDate() {
var dateROBD = format.parse({
value: new Date(),
type: format.Type.DATE
});
// this line optional if you want to try with or else ignore this
dateROBD = convertUTCDateToLocalDate(new Date(dateROBD));
return dateROBD;
}
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
OK, mystery solved. Turned out that this is not supported in SuiteScript 2.0 but you need to use 1.0.

Converting Excel date to Moment date gives a wrong year output

I am working on importing data in an Excel file and it has date column.
In my app, that date column value comes as a serial number like 43101.622083333335 which stands for 01/01/2018.
When converting this serial number from Excel back to the normal date it stands for, it gives wrong year.
For example, it gives 01-Jan-1970 instead of 01-Jan-2018
``
var moment = require('moment');
var excelDate = 43101.622083333335;
var date = moment(new Date(excelDate));
var dateWithNewFormat = date.format('DD-MMM-YYYY');
console.log(dateWithNewFormat);
``
Output: 01-Jan-1970 instead of 01-Jan-2018
Any help ?
Thanks in advance.
I don't think this is an issue with the moment library. It seems that you aren't calling Date with a valid constructor argument with new Date(excelDate) (see official documentation for Date here).
The Date class doesn't understand the concept of 'Excel time' but it does understand the concept of a unix timestamp. If you refer to this post, you can see how to convert from Excel time to a unix timestamp, depending on which version of Excel you are using.
Then, I would change your code to:
var moment = require('moment');
var excelDate = 43101.622083333335;
var unixTimestamp = (excelDate-25569)*86400 //as per the post above, convert Excel date to unix timestamp, assuming Mac/Windows Excel 2011 onwards
var date = moment(new Date(unixTimestamp)); //Pass in unix timestamp instead of Excel date
var dateWithNewFormat = date.format('DD-MMM-YYYY');
console.log(dateWithNewFormat);

setHour without change on Time Zone

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 :)

How to set DateTime Field Value without TimeZone in XPages ServerSide JS

When I set a value of Date/Time field in XPages It's value is like below.
I would like to set value without TimeZone (in this samples without ZE3).
Field Name: dtField1
Data Type: Time/Date
17.11.2016 13:13:31 ZE3
I tried #Today() and these 2 lines code below but I could not be succeded. is there any way to do it?
var now:NotesDateTime = session.createDateTime(#Now());
document1.replaceItemValue("dtField1", now);
Regard
C.A.
Time zone is always part of NotesDateTime field if field contains date and time no matter how you created it.
If the field contains date only or time only then time zone is omitted.
Set date only with
var now:NotesDateTime = session.createDateTime(#Now());
now.setAnyTime();
document1.getDocument().replaceItemValue("dtField1", now);
and time only with
var now:NotesDateTime = session.createDateTime(#Now());
now.setAnyDate();
document1.getDocument().replaceItemValue("dtField1", now);

Resources