I need to "GET" a date field from a "Record" and apply a timezone, in 1.0 it was just using the getDateTimeValue and passing the timezone as the second parameter. In 2.0 you only have the generic getValue and when passing the TZ as the second value or passing it in the options package, it seems to just ignore it. Anyone have an idea? I can't find it in the docs.
thanks in advance
In SuiteScript 2.0 you need to use the N/format module to apply the timezone to the raw date.
An example of usage is as follows:
require(['N/format'], function () {
var format = require('N/format');
var now = new Date();
console.log(now);
var nyTime = format.format({
value:now,
type:format.Type.DATETIME,
timezone:format.Timezone.AMERICA_NEWYORK
});
console.log('NY time is ' + nyTime);
var gmt = format.format({
value:now,
type:format.Type.DATETIME,
timezone:format.Timezone.GMT
});
console.log('London time is ' + gmt);
});
You can paste the above into the console of a new transaction page and run it to demonstrate how it's used.
Related
I've been searching for a while and can't find a definitive answer on that or any oficial documentation from AWS.
I have a Lambda function on which I need to get the current date according to my timezone, but I'm unsure on which premisses I may rely to do that, and as this is a critical app, I can't simply rely on a single test or empirical result.
I would expect that lambda functions follow the timezone of the AWS region that they are hosted in OR a unique timezone for any GMT 0, but couldn't confirm it anywhere.
Could anyone please clarify how this works and if possible also point to any official documentation about that? Also, any special concerns related to daylight saving time?
My Lambda function is written on NodeJS and what I've been doing locally (on my machine) to retrieve the current date time is using new Date().
Lambda time using the date object will return a date in UTC unix time
TZ – The environment's time zone (UTC).
To get a time in a specific timezone you can use moment-timezone.
Using Javascript Date().now():
var moment = require("moment-timezone");
moment(Date().now()).tz("America/Los_Angeles").format("DD-MM-YYYY");
or using new Date():
var moment = require("moment-timezone");
var date = new Date();
moment(date.getTime()).tz("America/Los_Angeles").format("DD-MM-YYYY");
You can change the moment .js format to whatever you require
Regarding daylight savings time, it is possible to detect it using isDST() method.
To avoid using an external library, you can use toLocaleString() which relies on Intl.DateTimeFormat().
You can pass it a locale and an option object that supports a "timezone" and other formating parameters.
var today = new Date(); //UTC in lambda
var localeDate = today.toLocaleString('fr-FR', { timeZone: 'Europe/Paris'}); // to get the full date string
var localeHour = today.toLocaleString('fr-FR', { timeZone: 'Europe/Paris',hour: 'numeric' }); //to get just the hour
console.log(localeDate);
console.log(localeHour);
If #bbas answer didn't work for you in nodejs14.x, try this out as mentioned in :
let date = new Date(); // UTC in lambda.
let dateString = new Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Kolkata', year: 'numeric', month: '2-digit', day: '2-digit'}).format(date);
console.log(dateString); // prints out date in mm/dd/yyyy in 'Asia/Kolkata' timezone
I am developing a chrome extension and it requires me to keep track of the last date that the extension was run. To do so, I am using chrome.storage.sync, however, the get call always returns the value that I have set as the default. Below is the code.
chrome.storage.sync.get({theDate: {}}, function (dateResult) {
let currentDate = new Date();
let setDate = dateResult.theDate; // always set to {}
if (Object.keys(setDate).length === 0){ //if date has never been set before
setDate = currentDate;
}
if (setDate.toLocaleDateString() !== currentDate.toLocaleDateString()){
//do stuff if it is a different day than the last time extension was run
}
chrome.storage.sync.set({theDate: currentDate}, function () {
console.log("Current date set.");
});
});
Chrome extension storage API supports only JSON-compatible types such as strings, numbers, booleans, and arrays/objects that consist of those primitive types.
A Date object isn't JSON'ifiable so it can't be stored.
You can store Date.now() which is a number.
chrome.storage.sync.get({theDate: Date.now()}, ({theDate}) => {
if (new Date(theDate).toLocaleDateString() !== new Date().toLocaleDateString()) {
// do stuff if it is a different day than the last time extension was run
}
chrome.storage.sync.set({theDate: Date.now()});
});
You need to stringify the Date objects before storing them. Use JSON.stringify or the String constructor. Alternatively, you can call Date as a normal function rather than a constructor to get string objects rather than a Unix Time Stamp; or, better yet as wOxxOm suggests, use Date.now() to get the date as a number in milliseconds. 1
I must also note that in the first conditional, you check if the Date object retrieved from storage has any keys, but it should not, even if you could store the raw Date object. You may be misunderstanding how data is set in storage. Essentially dateResult === {theDate: currentDate}, and dateResult.theDate === currentDate. 2
edit: include wOxxOm's suggestion for completeness.
I am using moment.js to format the date to relative time retrieved from the mongodb passed to the view from the express router.
Here is my .pug file:
extends ../LoginLayout/LoginLayout
block content
- var createdAt = requser.local.profile.createdAt
script(type="text/javascript").
$(document).ready(function() {
var createdAt = createdAt;
$('.memberSince')[0].innerHTML = moment().startOf(createdAt).fromNow(true);
});
.parallax-container.display
.parallax
img(src='http://lorempixel.com/1920/900')
.container.white-text.center
img.circle(src=requser.local.profile.dp style='width: 200px;')
h1 #{requser.local.name}
h6 Member Since #[span.memberSince #{createdAt}]
This the screenshot of the output in the browser:
MORE INFO
If I comment out this line from .pug file, this is the output (I guess pug automatically formats the date)
// $('.memberSince')[0].innerHTML = moment().startOf(createdAt).fromNow(true);
Any help would be appreciated, thanks.
And the actual date stored in my MongoDB database is in the format:
I solved this myself.
Actually, what I did miss was I would have to pass String to the moment.
Here is the solved .pug:
- var createdAt = requser.local.profile.createdAt
script(type="text/javascript").
$(document).ready(function() {
var createdAt = Date.parse('!{createdAt}');
console.log(createdAt);
$('.memberSince')[0].innerHTML = moment(createdAt).fromNow(true);
})
I was also getting the output by simply using var createdAt = '!{createdAt}', but in browser's developer console, it showed some depreciated warning of the passed string, so I parsed it to date using Date.parse(), and then passed the value as a string to moment().
Also, you can see that there was no need of .startOf() and I am passing the true param to fromNow() as it simply removes the suffix ago from the output, as per docs.
I can't seem to get hour12 time working in node.js, however in the browser (Chrome) it's working just fine.
Node.js in terminal
var date = new Date();
var d12 = date.toLocaleTimeString('en-US', {hour12:true});
var d24 = date.toLocaleTimeString('en-US', {hour12:false});
console.log(d12) // output 13:43:38
console.log(d24) // output 13:43:38
Both yeild the same result:
13:43:38
Update
Adding fiddle to prove it works in browser
Could someone point me to the docs that explain why, or tell me what I'm doing wrong?
It's not just you. I tried running the same chunk in Node.js and couldn't get a way to print it in 12 hour format easily.
After doing some Googling, it seems like Moment.js is a popular tool for manipulating and displaying time and days. If you need to manipulate a lot of time/dates, it may be worth checking out, Moment.js.
// with Moment
var moment = require('moment');
console.log(moment().format('hh:mm'));
Otherwise,
// just one of many ways to do it in Javascript
function hour12 (hour) {
var mod = hour % 12;
if (mod < 10) {
return '0'.concat(mod);
} else {
return mod;
}
}
console.log(new Date().toLocaleTimeString().replace(/[\d]+/, hour12(date.getHours())));
EDIT I answered this question late at night, and realized I sort of missed the mark on addressing the question.
Since Node.js is based off Chrome's v8 JavaScript engine, I started poking around in the source code. I can't see a place where it takes into account arguments passed to it.
Code is here, toLocaleTimeString is line 324. In comparison, I looked around Mozilla's SpiderMonkey engine and it at a glance, it seems to account for this.
You can use toLocaleDateString and toLocaleTimeString to format times and dates. The first parameter passed to these methods is a locale value, such as "en-us". The second parameter, where present, specifies formatting options, such as the long form for the weekday.
I've used Chrome and works well.
var date = new Date(Date.UTC(2016, 3, 7, 14, 30, 0));
var options = {
weekday: "long", year: "numeric", month: "short",
day: "numeric", hour: "2-digit", minute: "2-digit"
};
document.write(date.toLocaleTimeString("en-US", options));
https://msdn.microsoft.com/en-us/library/ff743760(v=vs.94).aspx
How do i format a timestamp inside the template? I followed a tutorial on building a chat and it works. Now i expanded the chat with some features like deleting the message and putting the time in front of the message. But when i write {{timestamp}} inside the template a UNIX timestamp is being given. How do i format it to show time like '6:12'. The timestamp is being stored in a Messages collection.
Is the right place to manipulate the timestamp inside of the
Template.Messages.created = function ( ) { ... }
function?
Thanks in advance.
Although not essential in this case, I would recommend using Moment.js, it makes working with dates and times in Javascript a breeze.
You can install the package from Atmosphere or download the script into your client dir then use a helper similar to the one below:-
Template.Messages.helpers({
created: function() {
var time = moment(this.timestamp);
return time.format('h:mm a');
}
});
NB: I've assumed timestamp is a var on the context object.
I use this library. It gives you all the date formatting you will ever need. With meteor just drop it in and you can use it in any helper to return the formatted date.
http://stevenlevithan.com/assets/misc/date.format.js
If you want to avoid libraries and manipulate with Javascript Date object I would suggest (this assumes that date is in ISO format 2010-06-15T00:00:00, wich you can get from Date.toISOString()):
Implement format method (thanks JavaScript equivalent to printf/string.format), put it in i.e. lib/utils.js:
String.prototype.format = function(args, index) {
return this.replace(/{(\w+)}/g, function(match, number) {
return typeof args[index[number]] != 'undefined'
? args[index[number]]
: match
;
});
};
Create helper (put it into client/client.js)
Handlebars.registerHelper('formatDate',function(input, pattern){
var iso = /^(\d{4})(?:-?W(\d+)(?:-?(\d+)D?)?|(?:-(\d+))?-(\d+))(?:[T ](\d+):(\d+)(?::(\d+)(?:\.(\d+))?)?)?(?:Z(-?\d*))?$/;
if(this[input]) {
var parts = this[input].match(iso);
return pattern.format(parts, {yyyy:1,MM:4,dd:5,hh:6,mm:7,ss:8,SSS:9});
}
return this[input];
});
Use the helper:
{{#each logs}}
<tr>
<td>{{formatDate 'ts' '{yyyy}-{MM}-{dd} {hh}:{mm}:{ss}'}}</td>
Have a look at this package swag which offers lots of useful handlebars helpers.
Checkout its date/time helpers: https://github.com/elving/swag#dates
You can format date/time as easily like:
var date = new Date()
{{formatDate date "%m/%d/%Y"}}
{{formatDate date "%I:%M%p"}}
{{formatDate date "%F"}}
{{formatDate date "%Y%m%dT%H%M%S%z"}}
07/26/2015
11:38PM
2015-08-28
20150828T233805-0004
Have a look at Template helpers and the JavaScript Date object.