Xpages Date Time - datetime

I'm going loopy....
I want a date, in date format, for example
21/06/2017 17:23:04 GDT
I stamp this on a document, but I then want to display it on my xpage as:
21/06/2017 17:23
But I keep getting different results no matter what I do. I get the date from the onClick of a button using
var dt = new Date();
I then pass this into a function:
function AddObjectivesHistoryItem(doc, dt, action, username){
var ArrDocHistory:array = doc.getItemValueArray("History");
if(ArrDocHistory.length < 1){
// This should always return an object as it is created when an objectives document is first
// created but do this check to be safe and create an array if for some reason it doesnt exist
ArrDocHistory = [dt+"|"+action+"|"+username];
}else{
// append new value to the array
ArrDocHistory.push(dt+"|"+action+"|"+username);
}
doc.replaceItemValue("History",ArrDocHistory);
doc.replaceItemValue("LastUpdatedByName",username);
doc.replaceItemValue("LastUpdatedDate",dt);
}
I've tried using toLocaleString() and all others it seems but it wont work.
For example, toLocaleString() displays as 13-Mar-2018 15:02:15 on my xpage. It's close to what I want except it uses hyphens instead of slashes, and also displays the seconds.
I've tried using custom date pattern on my date field properties with no luck and I'm certain I'm missing something super obvious!?
Any pointers on how to firstly get the date like 21/06/2017 17:23:04 GDT and store as a date and secondly to then display it as 21/06/2017 17:23, this can be a string if it needs to be.
Thanks

You can get your date value as String in SSJS with:
var dateTimeFormat = new java.text.SimpleDateFormat("dd/MM/yyyy kk:mm");
var dateTimeString = dateTimeFormat.format(dt)));

If you want to store as text, java.text.SimpleDateFormat is best for converting a date server-side to a specific text format. It can also be used in a converter to manipulate to/from as well.

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.

Function for Google Sheets' Script editor with a button for TODAY(), and NOW() in two different columns of which are the next not blank in the column

Currently, I'm looking at some simple documentation for vague ways to make a 'button' (image) over a Google sheet to trigger a function on the script editor. I'm not familiar with this type of Syntax, I typically do AutoHotKey, and a bit of python.
All I want to do is have this button populate 2 columns. The current date in one, and the current time in the other (It doesn't even have to have its year or the seconds tbh). I don't know if it matters of what the pages name is based on how the script works. So the range is ( 'Log'!G4:H ).
Like if I were to make it for AutoHotkey I would put it as :
WinGet, winid ,, A ; <-- need to identify window A = active
MsgBox, winid=%winid%
;do some stuff
WinActivate ahk_id %winid%
So it affects any page it's active on.
I would like to use the same function on the same columns across different sheets. Ideally, that is. I don't care if I have to clone each a unique function based on the page, but I just can't even grasp this first step, lol.
I'm not too familiar with this new macro. If I use this macro does it only work for my client, because of say like it recording relative aspect ratio movements?
IE if I record a macro on my PC, and play it on my android. Will the change in the platform change its execution?
If anyone can point me in any direction as to any good documentation or resources for the Google Sheet Script Editor or its syntaxes I would really appreciate it.
EDIT: Just to clarify. Im really focused in on it being a function that populates from a click/press(mobile) of an image. I currently use an onEDIT on the sheet, and it wouldnt serve the purposes that I want for this function. Its just a shortcut to quickly input a timestamp, and those fields can still be retouched without it just reapplying a new function for a newer current time/date.
EDIT:EDIT: Ended up with a image button that runs a script that can only input to the current cell.
function timeStamp() {
SpreadsheetApp.getActiveSheet()
.getActiveCell()
.setValue(new Date());
}
It only works on the cell targeted.
I would like to force the input in the next availible cell in the column, and split the date from the time, and put them into cells adjacent from one another.
maybe this will help... if the 1st column is edited it will auto-print date in 2nd column and time in 3rd column on Sheet1:
function onEdit(e) {
var s = SpreadsheetApp.getActiveSheet();
if( s.getName() == "Sheet1" ) {
var r = s.getActiveCell();
if( r.getColumn() == 1 ) {
var nextCell = r.offset(0, 1);
var newDate = Utilities.formatDate(new Date(),
"GMT+8", "MM/dd/yyyy");
nextCell.setValue(newDate);
}
if( r.getColumn() == 1 ) {
var nextCell = r.offset(0, 2);
var newDate1 = Utilities.formatDate(new Date(),
"GMT+8", "hh:mm:ss");
nextCell.setValue(newDate1);
}}}
https://webapps.stackexchange.com/a/130253/186471

Java 8 Parse ISO-8601 date ignoring presence (or absence) of timezone

My application should be able to parse date ignoring timezone (I always know for sure that it is UTC). The problem is that the date might come in both following forms -
2017-09-11T12:44:07.793Z
0001-01-01T00:00:00
I can parse the first one using LocalDateTime, and the second one using Instant class. Is there a way to do that using a single mechanism?
P.S. I'm trying to avoid hardcoding Z at the end of the input string
If the Z offset is optional, you can use a java.time.format.DateTimeFormatterBuilder with an optional section:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// date/time
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
// optional offset
.optionalStart().appendOffsetId()
// create formatter
.toFormatter();
Then you can use the parseBest method, with a list of TemporalQuery's that tries to create the correspondent object. Then you check the return type and act accordingly:
Instant instant = null;
// tries to create Instant, and if it fails, try a LocalDateTime
TemporalAccessor parsed = fmt.parseBest("2017-09-11T12:44:07.793Z", Instant::from, LocalDateTime::from);
if (parsed instanceof Instant) {
instant = (Instant) parsed;
} else if (parsed instanceof LocalDateTime) {
// convert LocalDateTime to UTC instant
instant = ((LocalDateTime) parsed).atOffset(ZoneOffset.UTC).toInstant();
}
System.out.println(instant); // 2017-09-11T12:44:07.793Z
Running with the second input (0001-01-01T00:00:00) produces the Instant equivalent to 0001-01-01T00:00:00Z.
In the example above, I used just Instant::from and LocalDateTime::from, so the formatter tries to first create an Instant. If it's not possible, then it tries to create a LocalDateTime. You can add as many types you want to that list (for example, I could add ZonedDateTime::from, and if a ZonedDateTime is created, I could just convert to Instant using toInstant() method).
As you know for sure that the input is always in UTC, you can also set it directly in the formatter:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// date/time
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
// optional offset
.optionalStart().appendOffsetId()
// create formatter with UTC
.toFormatter().withZone(ZoneOffset.UTC);
So you can parse it directly to Instant:
System.out.println(Instant.from(fmt.parse("2017-09-11T12:44:07.793Z"))); // 2017-09-11T12:44:07.793Z
System.out.println(Instant.from(fmt.parse("0001-01-01T00:00:00"))); // 0001-01-01T00:00:00Z
You can "parseBest", like this:
DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[Z]");
Temporal parsed = parser.parseBest(inputString, Instant::from, LocalDateTime::from);
Then you should check what did get parsed, and act accordingly.
The parseBest method will work with any type of TemporalQuery, including most of from methods available on java.time classes. So you can lengthen that list with LocalDate.from, for example.
You can also use that method and lambdas to coerse parse results to the type you want without having instanceof checks that are external for result resolution (although not without one cast):
Instant parsed = (Instant) parser.parseBest(inputString,
Instant::from,
interResult -> LocalDateTime.from(interResult).atZone(ZoneOffset.UTC).toInstant())
Notice that second option uses lambda that converts LocalDateTime to ZonedDateTime and then to Instant, so the parse results are always coersed to Instant.

EntityFunction.TruncateTime not working in my query

I am using Linq to entityframework to query some infomration. I am trying to use entityfunction.truncatetime and it doesnt seem to work as expected. here is my sample query
From d In Request
Where d.Requestor= "XXXX" And d.ProcessedFlag = "N"
Select d.RequestID, RequestReason = d.RequestReason.ItemValue, RequestType = d.RequestType.ItemValue, RequestedDate = EntityFunctions.TruncateTime(d.RequestedMoveDate)
The requesteddate doesnt seem to truncate the time part and I am still getting the both Date and time.
Am I missing something here?
In .NET, the DateTime class actually represents both a date and a time. Internally, this is stored as a numeric value represented by the number of 100-nanosecond "ticks" since Midnight, January 1, 1001 AD. This number gets "converted" when it's displayed (either in output or in a debugger). This conversion is done via a format string.
Even if you truncate a DateTime's time portion, it still has a time... it's just 00:00:00, and if you don't want to see that time, you need to adjust your format string to not convert that.
Thus, if you do something like this: DateTime.Now.Date it will display `10/15/2012 00:00:00" if you use the default date conversion string (or whatever is the default format for your culture).
If you want to only display the Date portion, then you must do something like myDate.ToShortDateString() or myDate.ToString("d").
EntityFunctions is a set of tools designed to be used in Linq to Entities queries, because doing DateTime formatting is not normally allowed in a query.
For example, this code does not work:
var q = from x in dc where x.BirthDate == DateTime.Now.AddYears(-15).Date select x;
You have to do it like this:
var q = from x in dc
where x.Birthdate == EntityFunctions.TruncateTime(DateTime.Now.AddYears(-15))
select x;
This will then generate the correct SQL to do date comparisons in SQL code. This is what the EntityFunctions are designed for, not truncating dates in the select portion (although it does work). But, even though the date is truncated, it will still have a Time component, it will just be 00:00:00, and you must use a date format string to present it to your users in the manner you intend.
cant you use ToShortDateString() like below?
List<DateTime> time = new List<DateTime>();
time.Add(DateTime.Now);
var WhatDate = from date in time
select new { Date = date.ToShortDateString() };
In your case try this
From d In Request
Where d.Requestor= "XXXX" And d.ProcessedFlag = "N"
Select new{ RequestID = d.RequestID, RequestReason = d.RequestReason.ItemValue, RequestType = d.RequestType.ItemValue, RequestedDate = d.RequestedMoveDate.ToShortDateString()};

xml and condition by dateTime

XML
<CalendarFairs>
<CalendarFair>
<DateStart>2011-04-05T00:00:00</DateStart>
<DateEnd>2011-04-09T00:00:00</DateEnd>
<Title>aaaa</Title>
<IdExecutive>1</IdExecutive>
</CalendarFair>
<CalendarFair>
<DateStart>2011-04-16T00:00:00</DateStart>
<DateEnd>2011-04-19T00:00:00</DateEnd>
<Title>bbb</Title>
<IdExecutive>2</IdExecutive>
</CalendarFair>
<CalendarFairs>
Code
var elements = from element in doc.Descendants("CalendarFair")
where DateTime.Parse (element.Elements ("DateStart").ToString())==DateTime.Now
select new
{
dateStart = element.Element("DateStart").Value,
dateEnd=element.Element("DateEnd").Value,
title=element.Element("Title").Value,
idExcutive = element.Element("IdExecutive").Value ,
};
foreach (var item in elements)//send this error
{}
System.FormatException: The string was not recognized as a valid DateTime. There is a
unknown word starting at index 0.
why error?
Try to change it as follows:
var elements = from element in doc.Descendants("CalendarFair")
let start = element.Element("DateStart").Value
where DateTime.Parse (start)==DateTime.Now.Date
select new
{
dateStart = start,
dateEnd=element.Element("DateEnd").Value,
title=element.Element("Title").Value,
idExcutive = element.Element("IdExecutive").Value ,
};
EDIT: based on the XML you have posted the query above works pretty well. Try to test it with this input:
<CalendarFairs>
<CalendarFair>
<DateStart>2011-04-05T00:00:00</DateStart>
<DateEnd>2011-04-09T00:00:00</DateEnd>
<Title>aaaa</Title>
<IdExecutive>1</IdExecutive>
</CalendarFair>
<CalendarFair>
<DateStart>2011-03-20T00:00:00</DateStart>
<DateEnd>2011-04-19T00:00:00</DateEnd>
<Title>bbb</Title>
<IdExecutive>2</IdExecutive>
</CalendarFair>
</CalendarFairs>
Note that I have inserted today's start date. Actually I think the result was empty just because there weren't entries with actual date.
It sounds like one or more of your input <DateStart> strings is not in a valid DateTime format.
Can you post some sample input XML?
It may be that you need to provide the date format using ParseExact - http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

Resources