I have a unix timestamp that I am trying to convert to the local timezone and then to render the .fromNow. However I can't seem to find the best way to convert to the local timezone and the current formatting technique cannot be used with .fromNow. Can someone point out what I am doing wrong with the formatting and how I can get the local timezone of the user?
Unix Example:
1541032289
Attempt:
moment(1541032289).format('YYYY MM DD').fromNow();
Error Message:
TypeError: moment(...).format(...).fromNow is not a function
UPDATE:
Code after replacing .format() with .unix()
Code:
store.zrevrange(zrangeSet, 0, -1, function(err, keys){
var range = [];
for (var i = 0; i < keys.length; i ++ ) {
var keyObj = JSON.parse(keys[i]);
keyObj.timestamp = moment().unix(keyObj.timestamp).fromNow();
range.push(keyObj);
}
console.log(range);
});
New Error:
keyObj.timestamp = moment().unix(keyObj.timestamp).fromNow();
^
TypeError: moment(...).unix(...).fromNow is not a function
There are two issues in your code. First, format returns a string while you should invoke fromNow() on moment objects. So, you can simply remove format('YYYY MM DD').
The second issue is that you have to use moment.unix(Number) instead of moment(Number).
As the documentation states:
To create a moment from a Unix timestamp (seconds since the Unix Epoch), use moment.unix(Number).
Here a live sample:
console.log( moment.unix(1541032289).fromNow() );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Related
I'm currently trying to connect a Lua Script with a GS WebApp. The connection is working but due to my lack of knowledge in GScripting I'm not sure why it isn't saving my data correctly.
In the Lua side I'm just passing in a hard-code a random name and simple numerical userid.
local HttpService = game:GetService("HttpService")
local scriptID = scriptlink
local WebApp
local function updateSpreadSheet ()
local playerData = (scriptID .. "?userid=123&name:Jhon Smith")
WebApp = HttpService:GetAsync(playerData)
end
do
updateSpreadSheet()
end
On the Google Script side i'm only saving the data on the last row and then add the value of the userid and the name.
function doGet(e) {
console.log(e)
// console.log(f)
callName(e.parameter.userid,e.parameter.name);
}
function callName(userid,name) {
// Get the last Row and add the name provided
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(sheet.getLastRow() + 1,1).setValues([userid],[name]);
}
However, the only data the script is saving is the name, bypassing the the userid for reasons I have yet to discover.
setValues() requires a 2D array and range dimensions should correspond to that array. The script is only getting 1 x 1 range and setValues argument is not a 2D array. Fix the syntax or use appendRow
sheet.getRange(sheet.getLastRow() + 1,1,1,2).setValues([[userid,name]]);
//or
sheet.appendRow([userid,name])
References:
appendRow
I want to store a Javascript Date() object in a spreadsheet with correct format according to spreadsheet's locale (SpreadsheetApp.getActive().getSpreadsheetLocale()).
Is there a way to get the country specific (date and) time format string from the spreadsheet locale?
E.g. when locale is de_DE, time format string as hh:mm
but when locale is da_DK, time format string as hh.mm
Interesting as well how to get the countries currency format.
BTW when I have date and time in de_DE and than change to da_DK, dates are reformatted (23.01.2020 -> 23/01/2020) but times are not (it stays as 22:59). Is that an error in Spreadsheet?
Dates in JavaScript have the method toLocaleDateString, which return a string formatted according to the specified locale. But this doesn't seem to work in Apps Script.
If you're open to using an Apps Script Web App for this, you could use this toLocaleDateString in your client-side script (that is, in a script tag in your HTML).
If that's not the case, I think your best option would be to create the relationship between formats and locales yourself, because Apps Script doesn't have a built-in method to achieve that. You could, for example, use a switch statement that would check the locale, and then format the date accordingly with Utilities.formatDate, the tool Apps Script uses to format dates. It could be something along the following lines:
var locale = SpreadsheetApp.getActive().getSpreadsheetLocale();
var formattedDate;
switch (locale) {
case 'de_DE':
formattedDate = Utilities.formatDate(yourDate, yourTimeZone, "hh:mm");
break;
case 'da_DK':
formattedDate = Utilities.formatDate(yourDate, yourTimeZone, "hh.mm");
break;
// ...
}
return formattedDate;
Reference:
toLocateDateString
Apps Script Web Apps
Utilities.formatDate
I hope this is of any help.
Sorry for that, however I found a function that would be worth checking out, it's toLocaleDateString() and toLocaleTimeString (), they deliver the local date and time format.
Please check
Formato fechas JavaScript.
I did the test from Google Apps Script and it throws me the following
function pruebafecha() {
var d = new Date();
var n = d.toLocaleDateString();
var h = d.toLocaleTimeString();
Logger.log(n);
Logger.log(h);
}
This is the answer(Colombia):
[20-01-24 16:47:50:286 EST] 24 de enero de 2020
[20-01-24 16:47:50:287 EST] 16:47:50 EST
A JavaScript Date object includes date, time and timezone. When Google Apps Script pass a Date object to the spreadsheet using setValue() / setValues() the value is displayed according to the cell number formatting using the spreadsheet timezone.
If the cell formatting is set to Automatic by default the date will be displayed accordingly to the spreadsheet locale.
If you want to force the cell to display a date in an specific format use Class Range setNumberFormat / setNumberFormats
If you don't want to use the above methods and don't want to rely on the spreadsheet locale and automatic cell format then instead of passing a Date object pass the value as an string prepending it with an ' (apostrophe, single quote character) to prevent that that automatic data type parsing changes the value and it's format.
Related
Javascript in Google Sheets script: help using setNumberFormat
I don't know very well the configuration of the sheet you mention. However, I share a code that I use to print the date and time of data submission of a form.
var d = new Date();
var hour = d.getHours()-1;
var min = d.getMinutes();
var day = d.getDate();
var month = d.getMonth()+1;
var year = d.getFullYear();
if (month<10) {dia = day+"/"+"0"+month+"/"+year;}
else {dia = day+"/"+month+"/"+year;}
if (min<10){time = hour+":"+"0"+min;}
else {time = hour+":"+min;}
What I do in the code is to take the values of day, month and year, I add 1 to the value of month because it takes values [0:11] => [Jan, Dec].
Then I build the format I want from date and time, you can notice that I have 1 left to the hours, because when I did the tests I noticed that the time of the script was one hour above.
I use google translate, I hope it is understood.
Quite simply, this is my code:
http://jsfiddle.net/NibblyPig/k9zb4ysp/
moment.locale('en-GB');
var d = moment('22/12/2019');
alert(d);
I would expect this to parse, however it says invalid date.
I have referenced moment.js and the locale/en-gb.js
I'm writing a global control so the date may come in in a variety of formats.
If I put in a variety of American dates they all work, for example 12/12/2019, 12/12/2019 23:04 etc.
However the locale command does not appear to do anything and I cannot get a single date to parse. What am I doing wrong?
You need to pass the format as the second argument for moment(), as discussed here:
moment.locale('en-GB');
var d = moment('22/12/2019', 'DD/MM/YYYY');
alert(d);
https://jsfiddle.net/a4gu6kfz/
From the docs:
If you know the format of an input string, you can use that to parse a
moment.
moment("12-25-1995", "MM-DD-YYYY");
I think that there is no need to write your own complex logic to parse your input, you can use moment(String, String) (or moment(String, String[], String, Boolean)), as suggested by Thales Minussi's answer.
moment(String) is the good choice only if your input is in ISO 8601 or RFC 2822 compliant form.
In your case, you can probably use Localized formats listed in the format section of the docs. If you have a list of possible formats, I think that the best choice is tho use moment(String, String[]).
Please note that, by default: Moment's parser is very forgiving, so using default Forgiving Mode will handle "any" character as separator.
Here a live sample:
moment.locale('en-GB');
['22/12/2019', '22/12/2019 15:00',
'22-12-2019', '22-12-2019 15:00',
'1-3-2019', '1-12-2019', '22-1-2019'
].forEach((elem) => {
var d = moment(elem, 'L LT');
console.log(d.format());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/locale/en-gb.js"></script>
Still hoping there's a nice moment js way to do this but in the meantime I just bashed this together. Pretty nasty and it will probably go wrong in 80 years or so.
http://jsfiddle.net/NibblyPig/k9zb4ysp/22/
var a = "23/03/19 12:42:21.123";
var datePart = a.substring(0, a.indexOf(" "));
var timePart = a.substring(a.indexOf(" ") + 1);
var dateParts = datePart.split("/");
if (dateParts[0].length == 1) dateParts[0] = "0" + dateParts[0];
if (dateParts[1].length == 1) dateParts[1] = "0" + dateParts[1];
if (dateParts[2].length == 2) {
var threshold = parseInt(new Date().getFullYear().toString().substring(2)) + 10;
if (parseFloat(dateParts[2]) > threshold ) {
dateParts[2] = "19" + dateParts[2];
}
else
{
dateParts[2] = "20" + dateParts[2];
}
}
alert (parseFloat(dateParts[2] + dateParts[1] + dateParts[0] + timePart.replace(/:/g, "").replace(/\./g, "")));
This won't solve every usecase, but in your specific example if you want just a simple date (with no time component) auto-parsed in UK format you can just use the 'L' format string having set the locale to 'en-GB'
Your example with this change (your jsfiddle also)
moment.locale('en-GB');
// just pass 'L' i.e. local date format as a parsing format here
var d = moment('22/12/2019', 'L');
alert(d);
It's quite nice because you get the auto parsing of various formats you wanted for free. For instance this works just the same:
var d = moment('22-12-2019', 'L');
You can return a date using moment.js in a desired format -
return moment(aDateVar).format('DD/MM/YYYY');
I want to use momentjs to check for invalid date/time strings:
var invalid = '2017-03-18 23;00;00';
if (moment(invalid).isValid()) {
return 'valid date'
}
This (correctly) throws a stacktrace with the familiar 'Deprecation warning: value provided is not in a recognized RFC2822 or ISO format......'
But even if I add a try/catch:
try {
var invalid = '2017-03-18 23;00;00';
if (moment(invalid).isValid()) {
return 'valid date'
}
catch (err) {
throw Error ('invalid date format');
}
the stacktrace is still printed.
What do I need to do to avoid the stacktrace from being printed?
I've searched all similar questions on StackOverflow but they all try to solve a different problem (fixing the input or finding the correct syntax to parse the input).
I using v2.18.1.
You have to use moment(String, String); to parse your input. If you don't want to specify a format (or an array of formats), you can use moment.ISO_8601. As the docs says:
Moment already supports parsing iso-8601 strings, but this can be specified explicitly in the format/list of formats when constructing a moment
This way you will not have deprecation warning. Here a working example:
var invalid = '2017-03-18 23;00;00';
if (moment(invalid, moment.ISO_8601).isValid()) {
console.log('valid date');
} else {
console.log('invalid date');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
PS. Anyway, if you have a list of accepted format, I suggest to use moment(String, String[]); (and strict parsing, if needed).
Specify the string format for your date then the warning will go away
moment("2017-1-27", 'YYYY-M-D').format('DD MMMM YYYY')
Below works for me to remove RFC2822 warnings
Use moment(String, FormatString) to convert string to date.
var newDt = Moment(this.state.dob,"MM/DD/YY")
And below code from date to String
var dt = Moment(newDt).format("YYYY-MM-DD")
By this way it will not show warning messages.
Adding .format() without any arguments to the moment expression that was causing that warning was the solution for me:
moment(r.created_at.toDate()).format()
I don't know any ASP.NET, and I need a function in Lua that can convert the date.
Example date: "\/Date(1397304050320)\/" --> 4/12/2014
Is the function below translatable to Lua?
If you don't know Lua can you try to translate the matching patterns for me?
I've already found this function:
function FixJsonDates(data) {
//microsoft script service perform the following to fix the dates.
//json date:\/Date(1317307437667-0400)\/"
//javasccript format required: new Date(1317307437667-0400)
//copied from micrsoft generated fiel.
var _dateRegEx = new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)(?:[a-zA-Z]|(?:\\+|-)[0-9]{4})?\\)\\\\/\\"', 'g');
var exp = data.replace(_dateRegEx, "$1new Date($2)");
return eval(exp);
}
To extract the date from a string and convert to a date, try
local s = "some text/Date(1397304050320)/more text"
local t = s:match("/Date%((%d+)%)/")
print(os.date("%D",t/1000))
In Lua, os.date requires times in seconds. Apparently the number you have is in milliseconds.