moment.js format date as iso 8601 without dashes? - momentjs

How do I format a date as iso 8601 using moment.js but without the dashes and colons and setting the time to 0 e.g. if I have a date like this:
2016-10-08T09:00:00Z
How do I format as :
20161008T000000Z
Doing moment(date).toISOString() gives 2016-10-08T09:00:00.000Z which is not what I want.

You can simply parse your input into a moment object and use startOf to set time to 00:00:00. Then you can use format method to get a string in your custom format.
Here there is a working example using a string input, you can use the same code also if your input is a javascript Date object.
// Input date as string
var s = '2016-10-08T09:00:00Z';
// Reset time part
// var m = moment(s).startOf('day'); // no UTC
var m = moment.utc(s).startOf('day'); // UTC mode
// Format using custom format
console.log(m.format('YYYYMMDD[T]HHmmss[Z]'));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>

Related

Get time format according to spreadsheet locale?

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.

MomentJS can't convert a date with format YYYY-MM-DD HH:mm:ss.fff Z

I am trying to convert the next date using MomentJS:
const moment = require('moment');
var datetime = "2017-11-19 02:45:22.011 +00:00";
var newDate = moment(datetime);
But it fails and the next message appears:
Deprecation warning: value provided is not in a recognized RFC2822 or
ISO format. moment construction falls back to js Date(), which is not
reliable across all browsers and versions. Non RFC2822/ISO date formats
are discouraged and will be removed in an upcoming major release.
Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more
info.
Snippet showing the issue:
var datetime = "2017-11-19 02:45:22.011 +00:00";
var newDate = moment(datetime);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>
I also tried using:
moment.utc(datetime);
but failed.
As moment(String) docs says:
When creating a moment from a string, we first check if the string matches known ISO 8601 formats, we then check if the string matches the RFC 2822 Date time format before dropping to the fall back of new Date(string) if a known format is not found.
2017-11-19 02:45:22.011 +00:00 is not in ISO 8601 compliant format because there is a space between fractional seconds and UTC offset (2017-11-19 02:45:22.011+00:00 is an ISO 8601 version of your input). So you can use moment(String, String), here a live sample:
var datetime = "2017-11-19 02:45:22.011 +00:00";
var newDate = moment(datetime, 'YYYY-MM-DDTHH:mm:ss.fff Z');
console.log(newDate.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>
Reformatting the date string from:
2017-11-19 02:45:22.011 +00:00
To:
2017-11-19T02:45:22.011Z
Solved it

Converting time format in simpleWeather.js

I want to convert the time from the standard 12-hour reading to the 24-hour one in simpleWeather. When I try to do it, it returns the time in the Unix epoch format.
$(function sunset(){
var sunset=
$.simpleWeather({
location:'Dalol,Afar',
woeid:'',
units:'f',
success:function(weather){
var Sunset= moment(weather.sunset, "HH:mm:ss");
html='Sunset: '+Sunset;
$('#sunset').html(html);
}
});
});
I had contacted the developer on how to do convert it using moment.js, but he didn't say much more than that. How can the code be corrected to display the desired format?
You need to first parse and then format the weather.sunset with the right formatting:
var sunset = moment(weather.sunset, ["h:mm A"]).format("HH:mm");
simpleWeather.js returns the sunset as "5:31 pm" so the corresponding moment format to parse this date is h:mm A, where the A captures the pm/am. To format it in the 24-hour notation, format("HH:mm") will do the job.

json.net deserialize datetime in object

I have a problem with deserialization of datetime. In JSON it comes in this format 2016-10-04T15:20:00 but after deserialialization it changes to the AM/PM time format and I need to preserve the 24 hour format. Is there any way how specify the format?
When you deserialize to a date, the format is not stored inside the date object. Instead, the formatting happens on output. The default format for your locale is probably using 12-hour time. If you want a different format, you can pass a format string to the ToString method:
string json = #"{ ""date"": ""2016-10-04T15:20:00"" }";
Foo foo = JsonConvert.DeserializeObject<Foo>(json);
Console.WriteLine(foo.Date.ToString("yyyy-MM-dd HH:mm:ss"));
Fiddle: https://dotnetfiddle.net/ibLCbG

Convert datepicker date to ISO format with moment.js

My task is to use a datepicker to pick a date in the prescribed format, eg(MM-DD-YYYY) and pass it to the server as ISO formatted.
While it test the output the ISO formatted date is one day behind.
For example
If i select
07-13-2015
My Output ISO format is
ISO format is :2015-07-12T18:30:00.000Z
Here you can see date is 13 but the output date is 12
I am from India. I tried with zone and utcOffset, ended up with no results. How do i set it right
Here is the JSFIDDLE
js code
$('#datetimepicker1').on("dp.change",function(e){
var selectedDate = $('#datetimepicker1').find("input").val();
selectedDate = moment(selectedDate,"MM-DD-YYYY");
$(".temp").text(moment(selectedDate).toISOString());
});
I do have a hidden field which value will be updated on change and that will be processed in the server. No issues on that.
$('#datetimepicker1').on("dp.change",function(e){
var selectedDate = $('#datetimepicker1').find("input").val();
selectedDate = moment(selectedDate,"MM-DD-YYYY");
$(".temp").text(selectedDate.toISOString());
});
Your selectedDate is already a moment object so you do not need to feed it back into another moment.
Example:
var test = '07-13-2015'
var mtest = moment(test,"MM-DD-YYYY")
mtest.toISOString()
"2015-07-13T06:00:00.000Z"
Your could try converting the date format to UTC at once.
selectedDate = moment(selectedDate).utc('MM-DD-YYYY')
According to http://dygraphs.com/date-formats.html, if you pass a string like '07-13-2015', it means Midnight of 13th July 2015. Now, if you use toISOString function, it will convert it to UTC by default. To not convert it to UTC, just pass a parameter true in the toISOString function. (Moment.js docs)
For example:
var date = '07-13-2015';
date = moment(date,'MM-DD-YYY');
console.log(date.toISOString(true));
This way, moment will not convert the date to UTC.

Resources