3

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

5 Answers 5

5

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.