I want to fetch the date and time when the report is generated in the form of ddMonyyyy-hhmm.
Currently I am using this code
string timeStamp = DateTime.Now.ToString("dd-mmm-yyyy"); DateTime date = DateTime.Now; timeStamp += "_" + Convert.ToString(date.Hour) + Convert.ToString(date.Minute);`` sFileName =sFileName+ timeStamp + ".xls";
But here the date and year are not getting fetched correctly.
Please help.
You can use hours and minutes in Format and it will take literals and just use them. Here are a couple examples. See more here DateTime.ToString Method
var result = DateTime.Now.ToString("dd-mmm-yyyy h:mm tt");
Standard Output:
07-17-2023 10:17 AM
var result = DateTime.Now.ToString("dd-mmm-yyyy_hhmm");
Standard Output:
07-19-2023_1019
var result = DateTime.Now.ToString("ddmmmyyyyhhmm");
Standard Output:
072120231021
As an aside, you may want to use UtcNow, not Now, unless all your users are in the same timezone or you wanted the time from the server.
Related
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.
[enter image description here][1]I need assistance in momentjs.
I’m using momentjs for date and time formats.
The issue I’m facing is that momentjs is displaying the current date and time instead of the correct date and time that is stored in the API.
Below is my code:(eventStartUTC) is the stored time in the API.
var startTime = moment(item.eventStartUTC).format("HH:mm" + " - ");
var endTime = moment(item.eventEndUTC).format("HH:mm");
var finalTime = startTime.concat(endTime);
Values for eventStartUTC and eventEndUTC as stored in the API:
item.eventStartUTC - "26/11/2017 06:00:00",
item.eventEndUTC - "28/11/2017 15:00:00"
date and time api values: https://i.stack.imgur.com/6ajO3.png
As moment(String) states:
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.
Since input (item.eventStartUTC and item.eventEndUTC) is neither in ISO 8601 nor RFC 2822 you have to use moment(String, String).
Here a live sample:
var item = {
eventStartUTC: '26/11/2017 06:00:00',
eventEndUTC: '28/11/2017 15:00:00'
};
var startTime = moment(item.eventStartUTC, 'DD/MM/YYYY HH:mm:ss').format("HH:mm" + " - ");
var endTime = moment(item.eventEndUTC, 'DD/MM/YYYY HH:mm:ss').format("HH:mm");
var finalTime = startTime.concat(endTime);
console.log(finalTime);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
I'm trying to process a form with a datetime-local field to create a calendar event in a public google calendar. But when I run the program, all my dates default to December 31st 1969 at 4pm. Anyone have any ideas?
My script (which takes "form" as a parameter):
var event = cal.createEvent(form.myTitle, new Date(form.startTime+".000Z"), new Date(form.endTime+".000Z"));
Logger.log(form.startTime+" and "+form.endTime);
I added ".000Z" as per this solution, but I ran into the same problem even without adding it: Why does my Date object in Google Apps Script return NaN
What startTime and endTime are logged as:
2016-03-15T17:30 and 2016-03-15T19:30
But this is in the execution transcript:
Calendar.createEvent([NEW EVENT, Wed Dec 31 16:00:00 PST 1969, Wed Dec 31 16:00:00 PST 1969])
There are lots of ways to set a date object in JavaScript, but to set the correct date for a Google Calendar, you must do it in a very specific way. You must get the calendar time zone. For many people, if the users of their script are all in the same time zone, then the code will work. The problem comes when you have users across different time zones, or the time zone of the script is different than the time zone of the calendar. The code must construct a valid date string first, and then use the date string to create the date object. You can create a date object without a date string, and that would be preferable in most cases, because people can mess up the code to create the date string, but in this situation, you have no other choice (That I know of). Why? It's because of the time zone offset setting. The time zone offset setting is included in the date string. That is the key piece of information, that makes sure your dates will get set correctly, including for daylight savings.
function setCalendarEvent(){
var startTime = "2016-03-15T17:30";
var endTime = "2016-03-15T19:30";
//Always get the time zone of the calendar. If you don't do that, users accross different times zones will write bad dates
var calTimeZone = CalendarApp.getDefaultCalendar().getTimeZone();
//Construct a valid date string from the data
var startYr = startTime.slice(0,4);
var endYr = endTime.slice(0,4);
var startMonth = startTime.slice(5,7);
var endMonth = endTime.slice(5,7);
var startDay = startTime.slice(8,10);
var endDay = endTime.slice(8,10);
var startHrAndMin = startTime.slice(11,17);
var endHrAndMin = endTime.slice(11,17);
var startDateString = startMonth + "/" + startDay + "/" + startYr + " " + startHrAndMin + ":00 ";
var timeZoneOffset = Utilities.formatDate(new Date(startDateString),calTimeZone, "Z");
var startDateAsDate = new Date(startDateString + " " + timeZoneOffset);
Logger.log('startDateAsDate: ' + startDateAsDate)
};
I'm developing a custom validator of a date input in my workflow form and I get a null after parsing a date this is what I done:
// check dates can be parsed
str_expiryDate = field.form.prop_wfbxTestWorkFlow_NfDate.value;
console.log("Non conformite"+str_expiryDate);
str_reminderDate = field.form.prop_bpm_workflowDueDate.value;
console.log("echeance"+str_reminderDate);
Alfresco.logger.warn("Expiry Date: " + str_expiryDate + " | Reminder Date: " + str_reminderDate);
d_expiryDate = Date.parse(str_expiryDate);
console.log("nfDate"+str_expiryDate);
d_reminderDate = Date.parse(str_reminderDate);
console.log("Date echéance"+d_reminderDate);
and then i get this in console:
Non conformite2013-06-21T00:00:00.000+01:00 echeance2013-06-09T00:00:00.000+01:00
nfDatenull
Date echéancenull
How I can parse these two dates and then compare it? .thanks
Use Alfresco.util.fromISO8601(date)
According to the client-api docs
Convert an ISO8601 date string into a JavaScript native Date object
You are parsing the "value" of a date, not the date itself.
The best way to compare is, imho, using the format YYYYMMDD, and than compare it as a number.
Something like this (there is sure a far more elegant way to do that, but at this time it's the only one that got me):
var indexDate=str_expiryDate.indexOf("-");
var dayDate=str_expiryDate.substring(0, 2);
var monthDate=str_expiryDate.substring(3, 5);
var yearDate=fromData.substring(6, str_expiryDate.length+1);
int dataNew=yearDate+monthDate+dayDate;
and than compare the two dates value.
Obviously check if the index value are correct, I didn't double checked them.
Hope il helps.
I'm parsing an XML file from an external source, and I have 2 attributes which contain the date and time respectively. I'm looking for the best way to get these into a format I can parse as a date so I can do things with it, but at the moment I'm just getting errors or no results with the methods I've tried.
The date is in the format "20111215" - which is yyyymmdd as it's UK based.
The time is formatted as "1417+0000" which I presume is the time plus offset from GMT?
Basically I need to get these into UK time. I've tried using DateTime.Parse on the separate parts but both give an error as not valid format. Tried String.Format on the date part but that didn't change it at all. I presume I need to combine the 2 before parsing but I'm not sure if I need to do anything else with it to make it acceptable.
Any help appreciated.
Use a DateTimeOffset to incorporate the timezone into the DateTime.
string date = "20111215";
string time = "1417+0500";
string dateAndTime = date + time;
string format = "yyyyMMddHHmmzzz";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTimeOffset t = DateTimeOffset.ParseExact(dateAndTime, format, provider);
If you concatenate the fields together, you can then use DateTime.TryParseExact in order to parse them into a DateTime.
string input = string.Format("{0} {1}", dateString, timeString);
DateTime parsed;
if(DateTime.TryParseExact(input,
"yyyyMMdd HHmmK",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out parsed))
{
// parsed OK, use the parsed variable
}
string date = "20111215";
string time = "1417+0000";
string dateString = date + time;;
string format = "yyyyMMddHHmmK";
// or something similar, I'm not sure about the timezone
DateTime result = DateTime.ParseExact(dateString,
format,
CultureInfo.InvariantCulture);
I think this should work (i didn't test it):
string dateString = "20111215";
string timeString = "1417+0000";
int year = int.Parse(dateString.Substring(0,4));
int month = int.Parse(dateString.Substring(4,2));
int day = int.Parse(dateString.Substring(6,2));
int hour = int.Parse(dateString.Substring(0,2));
int mins = int.Parse(dateString.Substring(2,2));
DateTime d = new DateTime(year, month, day, hour, mins, 0);