LINQ to SQL Get DateTime from Sql Server (getDate)

Ever wanted to get the current time and date from the SQL Server to avoid different times between yous server and the clients (for example having a centralized application running on many countries) ?

Using LINQ to SQL there is no way to get the time from the database build in the class. What you need to do is write your own code as the example below:

    using System.Data.Linq;
    using System.Data.Linq.Mapping;
    using System.Data;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Linq;
    using System.Linq.Expressions;
    using System.ComponentModel;
    using System;

    partial class dbGTOnlineDataContext
    {
        [Function(Name = "GetDate", IsComposable = true)]
        public DateTime GetSystemDate()
        {
            MethodInfo mi = MethodBase.GetCurrentMethod() as MethodInfo;
            return (DateTime)this.ExecuteMethodCall(this, mi, new object[] { }).ReturnValue;
        }
    }

Then anywhere in your code you can simple use the code below to get the time from the SQL Server database:

myDatabaseDataContext db = new myDatabaseDataContext();
DateTime dtNow = db.GetSystemDate();

4 Comments

  1. 😉

  2. ExecuteMethodCall ?

    • Hey, I have bought an upgdrae a week ago and things are not ok, for indeed even seeming it is alright, products in home are not appearing, and also any search I try to do, it shows errors like the ones below.:[Microsoft][ODBC Microsoft Access Driver] ORDER BY clause (customerTypesPrices.price) conflicts with DISTINCT./Comersus/includes/databaseFunctions.asp, line 57=========================another search gives (seems any search gives error)(Search criteria: Category .. ordered by: no ordering specified ) Microsoft VBScript runtime error ‘800a0006 Overflow: cint’/comersus/includes/itemFunctions.asp, line 273===========================and also the backoffice is not working.are there bugs in this items functions.asp or is something wrong with my db? By the way, I have a list of almost 70000 items (as it was in the former version and never had any problem).Paulo[] Reply:December 6th, 2012 at 1:38 amYou need to upgdrae your database structure to 9.10 before using 9.10 Power Pack. Upgrade DB utility is provided in Free Downloads Page.[]

  3. I value the knowledge on your site. Thank you so much!

Leave a Reply

Your email address will not be published. Required fields are marked *