Using MSSQL 2016 "AT TIMEZONE" feature from Entity Framework? - sql-server

How would one use the MSSQL 2016 AT TIMEZONE feature from Entity Framework?
In other words, how to generate
SELECT MyTimestamp AT TIME ZONE 'Central European Standard Time' FROM MyTable
by LINQ in entity framework ? Is it even supported yet ? Can one extend Entity Framework manually for this feature ?
There is always the option of creating a database-view with a time-zone column, but ideally I would like to avoid this extra view.

Couldn't you use a "model-defined function" in EF to create a functional expression that does at time zone thingy?
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/how-to-call-model-defined-functions-in-queries
<Function Name="TZ" ReturnType="Edm.DateTime">
<Parameter Name="date" Type="Edm.DateTime" />
<DefiningExpression>
date AT TIME ZONE 'Central European Standard Time'
</DefiningExpression>
</Function>
[EdmFunction("YourModel", "TZ")]
public static int TZ(DateTime date)
{
throw new NotSupportedException("Direct calls are not supported.");
}
#C:
from m as Mytable select new {TZ(s.MyTimestamp)};

Related

TDengine jdbc timezone

I used the code below to create timezone reconfigured connection.
operties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC+8");
Connection connDefault = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties);
and then I used the connDefault to create a statement,the use this statement to insert and select data.
insert into meters values('2021-07-29 00:00:00', 'taosdata');
select * from meters ;
But the java code query result is
ts=2021-07-29 16:00:00.0
there are 16 hours interval. While I expect the query result is the same as the insert time '2021-07-29 00:00:00'.
what's more the time stored in db is like this
ts | name
1627545600000 | taosdata
Query OK, 1 row(s) in set (0.008616s)
could someone help figure out why?
In addition, i found on the official website of tdengine always set timezone to "utc-8" does anyone know where that timezone is?
Properties connProps = new Properties();
connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
Like other database software, for example, PostgreSQL, TDengine uses Posix timezone spec which means the offset is opposite with the ISO 8601 standard.

Date error in DateProperty() save via ndb

Strange results on a saved date in GAE (Python with ndb library).
The inbound string from a web form is %a %m/%d/%y formatted (Fri 3/3/17).
That's parsed with datetime.strptime to get a date value.
When it's saved in a DateProperty() field, the value is consistently the day before, at 16:00:00.000 PST.
postDate = datetime.datetime.strptime(self.request.get('date-'+
hashed_id),'%a %m/%d/%y')
logging.info('postDate as Date: %s',postDate)
postDateStr = datetime.datetime.strftime(postDate,'%D')
logging.info('postDateStr: %s',postDateStr)
thisPost = ScheduledPost(id = postID,
...
postDate = postDate,
postDateStr = postDateStr
)
log results:
postDate as Date: 2017-03-03 00:00:00
postDateStr: 03/03/17
so far so good, right? but in the Datastore interface, that record shows:
PostDate: 2017-03-02 (16:00:00:000 PST)
PostDateStr: 03/03/17
Oops.
Workstation is in Pacific time - but leaving that aside - date queries seem to confirm that the date is wrong. Assuming today is 3/3/17 -
today = dt.datetime.now()
ScheduledPost.query(ScheduledPost.postDate == today).fetch()
No record returned.
Saving date as string, and querying on date as string, are feasible workarounds for this project. Just thought it merited posting - anyone seen this? Advice?
The datetime you're generating on appengine is UTC, and it gets stored as that datetime, without timezone information.
When you're viewing it, it's being converted to pacific-time.
The query you're doing is incorrect: you're generating a datetime, not a date, so the time you're comparing with is going to be different.

How do I Check for valid date in C# (that has a datetime type not datetime2)?

I've been searching but haven't found my answer so forgive me if this question is a duplicate.
I've got a .Net C# application that is using entity framework (EF) to communicate with a SQL Server database. I'm converting a large amount of data and I need to make sure my dates are valid SQL Server datetime types. My POCO classes use a datetime2 type for the dates so a date '0201-04-11 13:00:00 PM' is valid until the insert is actually attempted in the SQL Server database. I was attempting to use DateTime.TryParseExact with something like this...
if (DateTime.TryParseExact(legacyRecord.date_paid.ToString(), "M/d/yyyy hh:mm:ss tt", new CultureInfo("en-us"), DateTimeStyles.None, out datePaid))
{
// Load record into lease payment table table
LoadLeasePayment loadLeasePayment = new LoadLeasePayment();
Decimal LeasePaymentId = loadLeasePayment.AddRecord(prodLeaseId, legacyRecord.amount_paid, datePaid, prodContext, loadDate);
}
I'm sure the solution is obvious but I cannot see the forest for the trees. Any help is much appreciated.
After parsing the string DateTime value, you'll need to verify it is within the range of the target SQL data type. The SqlDateTime structure includes static MinValue and MaxValue fields to facilitate this.
if (DateTime.TryParseExact(legacyRecord.date_paid.ToString(), "M/d/yyyy hh:mm:ss tt", new CultureInfo("en-us"), DateTimeStyles.None, out datePaid))
{
if((datePaid >= SqlDateTime.MinValue) && (datePaid <= SqlDateTime.MaxValue))
{
// Load record into lease payment table table
LoadLeasePayment loadLeasePayment = new LoadLeasePayment();
Decimal LeasePaymentId = loadLeasePayment.AddRecord(prodLeaseId, legacyRecord.amount_paid, datePaid, prodContext, loadDate);
}
}

Convert DateTimeString to Ticks in DbMigration Entity Framework Compact CE

I need to change timestamp column in my compact ce 4.0 which currently is a string and formated:
"06.01.2016 22.18.47.977". To a column of type Long which holds DateTime.Ticks instead.
The DbMigration scripts proposal is obviously not what i want:
AlterColumn("dbo.LogRecords", "Timestamp",c => c.Long(nullable: false));
My initial thought was to use DATEDIFF to calculate number of millisecond*10.
DATEDIFF ( datepart , startdate , enddate ) *10=ticks
Unfortunatly it seems as if this function can only return int which fails with overflow.
Is there a way to do these kind of migrations in the migration script?
Ideally something like:
AlterColumn("dbo.LogRecords", "Timestamp",c => c.Long(nullable: false,
(p =>DateTime.ParseExact(p.Timestamp, "MM.dd.yyyy HH:mm:ss.fff", culture).Ticks));

How to get sysdate, time and timestamp from database using hibernate

In my application I need to get database date(sysdate in case of Oracle DB) and compare it with user input date (String converted to java.util.Date). From this forum I got the following code which helps in the case of Oracle dialect.
public Date getDate() {
Session session = getHibernateTemplate().getSessionFactory().openSession();
SQLQuery query = session.createSQLQuery("select sysdate as mydate from dual");
query.addScalar("mydate", Hibernate.TIMESTAMP);
return (Date) query.uniqueResult();
}
And from this link got the following method which uses mapping file with formula.
<property name="currentDate" formula="(select sysdate from dual)"/>
Again this is specific to Oracle. I think using later method is more performance friendly, because we can get it from the same session, i.e no need of opening another session just for getting date.
I am looking for a generic solution to get date, time and timestamp from any DBMS using Hibernate. Using HQL is the preferred. Hope such a solution is available.
For those who are looking for .NET /C# solution, here is what worked for me:
// this works only with Oracle
public DateTime DbTimeStamp(ISession session)
{
// Sample returned value = "12-OCT-11 01.05.54.365134000 AM -07:00"
string sql = "SELECT SYSTIMESTAMP FROM DUAL";
ISQLQuery query = session.CreateSQLQuery(sql)
.AddScalar("SYSTIMESTAMP", NHibernate.NHibernateUtil.DateTime);
return query.UniqueResult<DateTime>();
}

Resources