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.
Related
I'm confused.
I have a textbox that is populated with a date and time (string) such as '09/07/2021 10:30'.
I convert this string to a moment like so:
var suggestedDateObj = moment(suggestedDate, 'DD/MM/YYYY HH:mm');
I then want to check if this date and time is in between time slots in a fullcalendar.js event object. I do this like so:
var startDateObj = moment(value.start);
var endDateObj = moment(value.end);
if (suggestedDateObj.isBetween(startDateObj, endDateObj)) {}
However...it isn't working. And it's due to timezone offset (i think).
suggestedDateObj returns a value with a UTC offset of +0100 (British Summer Time)
However my calendar event objects return a date with a UTC offset of +0000. So when i check if '09/07/2021 10:30 +0100' is in between '09/07/2021 10:30 +0000' and '09/07/2021 11:30 +0000' it doesn't work!
I guess my question is really either:
How can I create my suggestedDateObj moment with a timezone offset of zero? OR
How can i tell fullcallendar events that the time it is displaying is actually BST (+0100)? At the moment I don't specify the 'Timezone' parameter.
Thanks.
UPDATE
Hmm....this might work....although it feels a bit clunky:
var tmoment1 = moment(suggestedDate, 'DD/MM/YYYY HH:mm');
//create default date with specific timezone offset of zero
var suggestedDateObj = moment().utcOffset(0);
//set the date and time
suggestedDateObj.set({
day: tmoment1.day(),
month: tmoment1.month(),
year: tmoment1.year(),
hour: tmoment1.hour(),
minute: tmoment1.minute(),
second: 0
});
You can generate suggestedDateObj in utc like that:
var suggestedDateObj = moment.utc(suggestedDate, 'DD/MM/YYYY HH:mm');`
For the .isBetween() I suggest you to use the square bracket like forth parameter, like documentation says.
if (suggestedDateObj.isBetween(startDateObj, endDateObj, undefined, '[]'))
The square brackets indicate that the check must include the dates of the limiter
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.
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
This is my code in js:
var x = "2017-1-2";
var y = moment(x, "yyyy-MM-DD")
And when I watch y in console this is what it is:
As you can see, the _d has the correct day and monthe, but the wrong year. Why is this happening and how to fix it? I use that value to send it to server via ajax and the wrong year gets sent.
Use uppercase YYYY instead. It is mentioned in the docs. Also don't forget that construction using moment() will treat the date as local date and then convert it into UTC. If you want to treat the date as UTC, you can use moment.utc().
In my timezone (GMT+7) the code below will show "2017-01-01T17:00:00.000Z".
var x = "2017-1-2";
var y = moment(x, "YYYY-MM-DD")
console.log(y);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script>
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>