Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 466
kk. Avatar asked Nov 21 '25 00:11

kk.


2 Answers

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;
like image 98
AnthonyWJones Avatar answered Nov 22 '25 13:11

AnthonyWJones


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.

like image 28
JaredPar Avatar answered Nov 22 '25 14:11

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!