Subin Jacob
Subin Jacob

Reputation: 4864

How to get correct time on client side javascript?

Currently, I have a datetime field in one of my sqlserver table. And I Query (SELECT Column1, myDateField FROM MyTimeTable BETWEEN @startDate AND @endDate). NOW I got Column1, myDateField at C# code side using Entity framework.

Problem

Then I'm passing these dates to client side as json. Now, asp.net converts date to "\/Date(1410588000000)\/" format. (ie date '19-9-2014' to 1410588000000). When I create date with this ticks (From 1970 ticks of javascript) it will add extra 5.00 hours (server timezone is -5.00). This happens because while converting datetime to "\/Date(xxxxxxxxx)\/" format, .net consider the date in database (ie, now a c# datetime using entity framework) is local (-5.00). So it creates ticks for +5.00 hours. How can I convince .net that the time is in utc?

Upvotes: 0

Views: 515

Answers (2)

JJRS
JJRS

Reputation: 37

Please convert your DATE TIME to any fixed specific format and than follow it every where, So it will help you to maintain the consistency.

Write query like below

SELECT CONVERT(VARCHAR(30),GETDATE(),113) AS DateConvert;

Format will be "dd MMM yyyy hh:mm:ss:zzz" this will send exact date time format , which will be converted easily. Hope this will help you.

Now we can use DateTime.ParseExact to convert received string (Date) to DateTime

C# code

  String dateString = "01 Jun 2008 08:30:06:00";
  CultureInfo provider = CultureInfo.InvariantCulture;
  String format = "dd MMM yyyy hh:mm:ss:zzz";
  try {
     DateTime result = DateTime.ParseExact(dateString, format, provider);
  }

Thanks

Upvotes: 1

Karthik AMR
Karthik AMR

Reputation: 1714

Var date = new Date();

now the date have the value of client's time.

alert(new Date());

Upvotes: 0

Related Questions