kk.
kk.

Reputation: 687

sending javascript date to vb.net date variable

I need to pass javascript date value to vb.net function.

Method iam using now: convert javascript date to string store it in hiddenfield retrieve string from hidden field in server code and parse it using date.parse

the trouble is that the Javascript dateformats

toString() - Sat Apr 4 22:19:00 UTC+0530 2009

toDateString() - Sat Apr 4 2009

toLocaleString() - Saturday, April 04, 2009 10:19:00 PM

doesnt match vb date format. I am getting error that its unparseable.

Thanks in advance for the help

Upvotes: 3

Views: 4847

Answers (5)

kk.
kk.

Reputation: 687

Since I don't have to worry about culture difference I am going to use toLocaleString().

toLocaleString() parses fine to a string compatible with Date.Parse().

Anyway thanks for posting your replies.

Upvotes: 1

AnthonyWJones
AnthonyWJones

Reputation: 189447

The problem with using ToLocaleString is that you lose timezone info and its obviously locale specific which means you need to parse it with the right culture.

I was thinking:-

DateTime d = DateTime.ParseExact(sInput, "ddd MMM d HH:mm:ss UTCzzzz yyyy" , CultureInfo.InvariantCulture);

But that isn't cross browser compliant (the ECMA spec does not define what toString should actually do).

However we do know that the value of a Javascript Date object is the number of milliseconds from midnight Jan 1, 1970. Hence you could instead store the .valueOf of a date object in your hidden field. Use Int32.Parse on the string first, create a TimeSpan from the that value and add it to a DateTime of Jan 1, 1970 00:00:00 UTC+0000.

int milliseconds = Int32.Parse(inputString);
TimeSpan t = TimeSpan.FromMilliseconds(milliseconds);
DateTime base = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime result = base + t;

Upvotes: 5

Joel Coehoorn
Joel Coehoorn

Reputation: 415665

You can also use DateTime.ParseExact() to tell the VB code exactly what the incoming string should look like.

Upvotes: 0

Kthevar
Kthevar

Reputation: 1547

This just a datetime formating issue can you look this post for more details. How we can resolve the datetime problem shifting the Access DB from production server to live

Upvotes: 0

JaredPar
JaredPar

Reputation: 754575

Why not instead pass the Javascript date as a string and then convert it to a date type in VB.net.

Public Function ConvertJavaScriptDate(ByVal d as String) As Date
  Return Date.Parse(d)
End Function

Another option is to use CType(d,Date). CType is a lexical cast that will try a variety of ways to convert the string value to a Date.

I'm not terribly familiar with the difference between a JavaScript Date and a VB.Net Date in terms of format, but if you post an example I'm sure we can get a basic conversion going.

Upvotes: 1

Related Questions