sending javascript date to vb.net date variable - javascript

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

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;

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.

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.

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

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

Related

Javascript input a UTC string

I'm working on a project right now where I want to get an array of dates between two end points. I've got that code working perfectly when I hard code the start and end date in.
My problem is when I used an input, the code doesn't work. How can I convert a normal date input into a UTC string?
Here's an example of what I'm on about: https://jsfiddle.net/mksvh95y/5/
<input type="date" id="bubbles" placeholder = "enter date">
<button onclick="getDate()"> Click me to get date</button>
<script>
function getDate(){
var water = document.getElementById("bubbles").value;
alert(water);
//alert(water.toUTCString());
var fire = new Date (2018,10,15);
alert(fire);
}
I want the get the 'water' variable to be formatted like the 'fire' variable.
I saw there's .toUTCstring(), but that doesn't work
This is possibly a duplicate of Why does Date.parse give incorrect results, but here's an answer that may be more suitable.
The value of a date input is an ISO 8601 format date string in the format "YYYY-MM-DD", which is what you should see from:
alert(water); // something like 2018-06-21
The format of the string returned by Date.prototype.toString is implementation dependent (though ECMAScript 2019 will standardise it). That's the format you're getting from:
alert(fire) // e.g. Thu Jun 21 2018 00:00:00 GMT+1000 (AEST)
One fix is to convert the string from the date input to a Date, then use the default toString for both outputs. But your problem then is that parsing of the ISO 8601 date string is UTC, so the dates will be different by the host timezone offset, e.g.
console.log(new Date('2018-06-21').toString()); // 21 Jun 2018
console.log(new Date(2018, 5, 21).toString()); // 21 Jun 2018
So you need to parse the string from the input as local using a simple function like:
function parseISOLocal(s) {
var b = s.split(/\D/);
return new Date(b[0],b[1]-1,b[2]);
}
console.log(parseISOLocal('2018-06-21').toString());
console.log(new Date(2018, 5, 21).toString());
If you want to use a library like moment.js, it will parse ISO 8601 formatted date strings as local (which is consistent with ISO 8601), then convert it to a plain Date and use the default toString, e.g.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<input type="date"
onchange="console.log(moment(this.value).toDate().toString())">
I strongly recommend using the excellent MomentJS library for date mainpulation, as native support is poor:
function getDate(){
var water = document.getElementById("bubbles").value;
var waterMoment = moment(water);
alert(water.utc().format()); //outputs a UTC date string
var fire = new Date (2018,10,15);
alert(fire);
}
See the moment.utc() function and the moment.format() function for more details.

Javascript date stored in a C# string to C# Datetime

how can I convert "/Date(1479250800000)/" String to a C# Datetime?
Thanks in advance
Assuming the value inside the brackets is number of ticks:
var datstr = "/Date(1479250800000)/";
long ticks = Convert.ToInt64(datstr.Substring(6, 13));
DateTime date = new DateTime(ticks);
There will be a difference between .Net and javascript tick value:
The JavaScript Date type's origin is the Unix epoch: midnight on 1 January 1970. The .NET DateTime type's origin is midnight on 1 January 0001. If by "ticks" you mean something like "milliseconds since the epoch", you can call ".getTime()
There are 621355968000000000 epoch ticks for javascript from Ist Jan 1900 to Ist Jan 1970. And here 10000 are the ticks per milliseconds.
quoted from here. You will need to correct for this. the last line would look like the following:
DateTime date = new DateTime(ticks * 10000 + 621355968000000000);
You'll get the string "/Date(1479250800000)/" as a date value in javascript if you are sending it from C#. But if you sending back the value to a date field in C# then the value will be deserialized as DateTime value. You don't need to convert it explicitly, just get it in a DateTime field.

Javascript Date toJSON() outputting incorrect date

I am based in Australia and while new Date() give me the current date and time in Australia, for instance
Fri Aug 26 2016 09:16:16 GMT+1000 (AUS Eastern Standard Time)
, if I write new Date().toJSON()
I get 2016-08-25T23:20:08.242Z,
how can I get the same format as in yyyy-mm-ddThh:mn:ss but keeping my local day and time, ie it should be the 26 and not the 25th.
Edit: when I write programmatically new Date(2016, 11, x) with var x = 31, using toJSON() I have no guarantee to see displayed 2016-12-31 because of timezones, so was wondering is there is a different javascript function that would give me the intended result.
I would use moment.js for that.
var date = moment("Fri Aug 26 2016 09:16:16 GMT+1000");
console.log(moment(date).format('YYYY-MM-DD T hh:mm:ss'));
https://jsfiddle.net/Refatrafi/ys4nu8o9/
toJSON() returns timestamps in ISO 8601 format. Z at the end of string means that used UTC. Date objects in ECMAScript are internally UTC. The specification for Date.prototype.toJSON says that it uses Date.prototype.toISOString, which states that "the timezone is always UTC".
The date isn't wrong, it's in UTC. Without timezone information, yyyy-mm-ddThh:mn:ss is meaningless unless you explicitly want to assume that it's in the AEST timezone.
If you're transmitting the date as a string to be parsed back into some sort of Date-like object later on (by your webserver, for example), there's nothing you need to do. 2016-08-25T23:20:08.242Z unambiguously refers to the same point in time no matter what you use to parse it.
If you're trying to format the date object and display it somewhere, you can extract the different parts of the Date object and build up the representation you want:
function format_date(d) {
var pretty_date = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join('-');
var pretty_time = [d.getHours(), d.getMinutes(), d.getSeconds()].join(':');
return pretty_date + 'T' + pretty_time;
}
As the other answers have pointed out, if you plan on working more with dates, consider using a library that makes it easier. JavaScript doesn't have a very rich API, so you'll have to write more code.

Convert ISO Date string to date in JavaScript

Need help to convert exactly from ISO Date string to Date:
I have an ISO string date: "2016-01-23T22:23:32.927".
But when I use new Date(dateString) to convert Date, the result is wrong:
var date = new Date("2016-01-23T22:23:32.927");
The result is: Sun Jan 24 2016 05:23:32 GMT+0700. It's not true. I want the date is 23 not 24.
Please help me. Thanks a lot!
You need to supply a timezone offset with your iso date. Since there isn't one, it assumes the date to be in GMT and when you log it out, it prints it in the timezone of your browser. I think that if you pass "2016-01-23T22:23:32.927+07:00" to new Date() you would get the value you are expecting.
JavaScript environments (browser, node,...) use a single timezone for formatting dates as strings. Usually this is your system's timezone. Based on the output you get, yours is GMT+0700.
So what happened:
The string you passed as ISO format to the Date constructor doesn't specify a timezone. In this case it is treated as UTC.
When you then output the date (I'll assume with console.log), it is converted to the timezone of your environment. In this case 7 hours where added.
If that doesn't suit you, you can change the way you output the date. This depends on what output you want, e.g.:
If you just want the UTC timezone again, you can use date.toISOString().
If you want to output it in another timezone, you can call date.getTimezoneOffset() and figure out the difference between both timezones. You'd then probably need to get the individual date parts and add/subtract the timezone difference accordingly. At this point you could consider using an existing library, taking into account their possible disadvantages.
If you're willing and able to add a dependency, I recommend using moment.js for this. It makes date handling in Javascript much more straightforward and a lot safer, and fixes your specific problem right out of the box.
To do this, 1st load it from a CDN, e.g. Moment.JS 2.14.1 minified. Then use it as follows:
var date = moment("2016-01-23T22:23:32.927");
console.log(date);
// output: Sat Jan 23 2016 22:23:32 GMT-0500
...i.e. your desired result :)
Here's a jsfiddle demonstrating this.
Use date.toUTCString()
it'll give you 23 instead of 24 as it Convert a date object to a string, according to universal time

How do I convert to browser timezones using phstc dateFormat?

EDIT : Btw, I have no idea why this question was marked as a duplicate. The answers in the original question does not work for me. i.e, getting wrong results and stuffs. Furthermore, none of the answers deal with phstc's dateFormat function. Do correct me if I'm wrong. Btw, I have solved this question. Do take a look at my answer.
I want to change a UTC datetime to my browser's timezone. I'm using phstc's dateFormat in pure javascript form. Let's say I convert a datetime of 2014-06-27 07:11:16 using a javascript Date() function. The result I got was
Fri Jun 27 2014 07:11:16 GMT+0800 (Malay Peninsula Standard Time)
Then when I use phstc's toBrowserTimeZone function, it still returns me the same datetime. I wanted to get something like 2014-06-27 15:11:16
Here is the code below:
var originalDateTime = new Date(`2014-06-27 07:11:16`);
alert(DateFormat.format.toBrowserTimeZone(originalDateTime,"yyyy/MM/dd HH:mm:ss"));
According to this statement in phstc's dateFormat page,
value = String representing date in ISO time (ā€œ2013-09-14T23:22:33Zā€) or String representing
default JAXB formatting of java.util.Date (ā€œ2013-09-14T16:22:33.527-07:00ā€) or String representing
Unix Timestamp (Sat Sep 14 2013 16:22:33 GMT-0700 (PDT)) or javascript date object.
JS Date object should work but unfortunately, it didn't. Well, I got it fixed by changing the datetime to other formats stated above first before calling the toBrowserTimeZone() function. For example,
var originalDateTime = DateFormat.format.date('2014-06-27 07:11:16',"yyyy-MM-ddTHH:mm:ssZ");
var newDateTime = DateFormat.format.toBrowserTimeZone(originalDateTime);

Categories

Resources