EntityFunction.TruncateTime not working in my query - asp.net

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()};

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.

Xpages Date Time

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.

Parse alfresco date

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.

Compare two different date formats in a query

I have to compare a user entered date, "Dt" (in mm/dd/yyyy format) with the date in RavenDB - "ReleaseDate" (time stamp like "/Date(1187668800000)/"). For this I am using the following code which almost gets the job done, but I need little help to finalize loose ends...
How can I compare the two dates so I can get the query to run successfully.
public ActionResult Calculation(DateTime? Dt)
{
var store = new DocumentStore { Url = "http://localhost:80" };
store.Initialize();
var CalcModel = new CalcViewModel();
using (var session = store.OpenSession())
{
//Converting user entered date dt in mm/dd/yyyy format to total
//milliseconds - So that later I can compare this value to RavenDB
//time stamp date format (older versions)
DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = Dt.Value.ToUniversalTime();
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
double tmillisecs = ts.TotalMilliseconds; //Not yet using this value.
CalcModel.MoviesByDate = session.Query<Movies>()
.Where(x => x.ReleaseDate.Ticks == ts.Ticks)
.Count();
// this is where I need to compare two dates - ts.ticks gives the
// required value of date (1187668800000) multiplied by 10000.
}
return View(CalcModel);
}
Right now, when I debug I know what value ts.ticks is showing... and its like I said above in the code comments, the required value multiplied by 10000. But I have no clue at run time , what the value in x.ReleaseDate is or x.ReleaseDate.Ticks is.. am I doing this correctly. Thanks for the help.
Umm... I think you seriously misunderstand how SQL dates work, and how it applies to .NET. The whole point about dates is that they're stored in a numeric format, not a text one. So when you have a DateTime object, it's not stored as the text date, it's stored as a numeric type that you can convert to any format you want.
Because the .net provider converts database native datetime objects to DateTime objects, you can just compare them natively. ie:
DateTime d1 = new DateTime(1970, 1, 1);
CalcModel.MoviesByDate = session.Query<Movies>()
.Where(x => x.ReleaseDates.Date == d1.Date)
.Count();
Regardless of how RavenDB stores the dates internally, when the DateTime object is materialized in the query, it will be in native .NET format.

Linq-to-entities date value in database is string

Personally, I know just enough Linq to be dangerous.
The task at hand is; I need to query the DAL and return a list of objects based on a date range. Sounds simple enough, however the date is a string, and for some reason it needs to stay a string.
I spent some time with this a while ago and got a solution working but I am iterating through a list of objects and selecting individual records by date one at a time, this is badddd! If the date range spans more than a few days its slow and I don't like it, and I've even busted a few of the Sr devs around here for doing iterative queries, so I definitely don't want to be a hypocrite.
Here is the crappy iteration way... each date pegs the database, which I hate doing.
- This works
DateTime start = Convert.ToDateTime(RecipientSearch.TransplantSearchStartDate);
DateTime end = Convert.ToDateTime(RecipientSearch.TransplantSearchEndDate);
var tempselectQuery = selectQuery;
while (start <= end)
{
tempselectQuery = selectQuery;
string sStart = Convert.ToDateTime(start).ToString(ResourceFormatting.DateOnly);
tempselectQuery = (ObjectQuery<DAL.Recipients>)tempselectQuery.Where(item => item.TransplantDate == sStart);
if (tempselectQuery.Count() != 0) TXPlistQueryDAL.AddRange(tempselectQuery.ToList());
start = start.AddDays(1);
}
Here is my attempt at trying to get my query to work in one db call
- This does not work... yet
DateTime start = Convert.ToDateTime(RecipientSearch.TransplantSearchStartDate);
DateTime end = Convert.ToDateTime(RecipientSearch.TransplantSearchEndDate);
List<string> sdates = new List<string>();
// Put my date strings in a list so I can then do a contains in my LINQ statement
// Date format is "11/29/2011"
while (start <= end)
{
string sStart = Convert.ToDateTime(start).ToString(ResourceFormatting.DateOnly);
sdates.Add(sStart);
start = start.AddDays(1);
}
// Below is where I get hung up, to do a .contains i need to pass in string, however x.TransplantDate
// includes time, so i am converting the string to a date, then using the EntityFunction to Truncate
// the time off, then i'd like to end up with a string, hence the .ToString, but, linq to entities
// thinks this is part of the sql query and bombs out... This is where I'm stumped on what to do next.
selectQuery =
(ObjectQuery<DAL.Recipients>)
from x in entities.Recipients
where sdates.Contains(EntityFunctions.TruncateTime(Convert.ToDateTime(x.TransplantDate)).ToString())
select x;
The error i get as follows:
I understand why I get the error, but I don't know the proper LINQ code to be able to acheive what I am trying to do. Any help will be greatly appreciated.
Ughh I feel dumb. I tried a bunch of tricky little things to get x.TransplantDate to just a date only string within my Linq query, E.G. 10/15/2011
where sdates.Contains(EntityFunctions.TruncateTime(Convert.ToDateTime(x.TransplantDate)).ToString())
Turns out it already is in the correct format in the database, and if i simplify it down to just
where sdates.Contains(x.TransplantDate) It works. The reason I wasnt getting any records returned was because I was testing date ranges that didnt have any data for those specific dates... UGHH.
So in conclusion this ended up working fine. And if anyone is doing something similar maybe you can learn from this example.
DateTime start = Convert.ToDateTime(RecipientSearch.TransplantSearchStartDate);
DateTime end = Convert.ToDateTime(RecipientSearch.TransplantSearchEndDate);
List<string> sdates = new List<string>();
while (start <= end)
{
string sStart = Convert.ToDateTime(start).ToString(ResourceFormatting.DateOnly);
sdates.Add(sStart);
start = start.AddDays(1);
}
selectQuery =
(ObjectQuery<DAL.Recipients>)
from x in entities.Recipients
where sdates.Contains(x.TransplantDate)
select x;

Resources