Parsing a Auto-Generated .Net Date Object with JavaScript/Jquery

Parsing a Auto-Generated .NET Date Object with Javascript/JQuery

The link from Robert is good, but we should strive to answer the question here, not to just post links.

Here's a quick function that does what you need. http://jsfiddle.net/Aaa6r/

function deserializeDotNetDate(dateStr) {
var matches = /\/Date\((\d*)\)\//.exec(dateStr);

if(!matches) {
return null;
}

return new Date( parseInt( matches[1] ) );
}

deserializeDotNetDate("/Date(1304146800000)/");

Converting Date with Javascript

Your snippet, perhaps unknown to you, actually tries to pass a regular expression literal to the Date constructor. What comes back from your API is actually a string - of the form /Date(xxx)/ where xxx appears to be a Unix timestamp. In order to translate this to a Javascript date object, we need to parse the timestamp out of that - assuming the data always has this format - and ironically, the simplest way to do that is probably a regular expression:

const oldDate = "/Date(1570474808430)/";

const timeStamp = Number(oldDate.match(/\/Date\((\d+)\)\//)[1]);

const updatedDate = new Date(timeStamp);

console.log(updatedDate)

Date time conversion in Javascript from format /Date(1535515200000)/

var s = "/Date(1535515200000)/";
var ts = s.substring(s.indexOf('(')+1,s.lastIndexOf(')'));
console.log(new Date(Number(ts)).toISOString());

Would print "2018-08-29T04:00:00.000Z"

How to parse JSON to receive a Date object in JavaScript?

There is no standard JSON representation of dates. You should do what @jAndy suggested and not serialize a DateTime at all; just send an RFC 1123 date string ToString("r") or a seconds-from-Unix-epoch number, or something else that you can use in the JavaScript to construct a Date.

Parsing the C# datetime to javascript datetime

new Date(object.MyDate); should work.

EDIT:
var date = new Date(parseInt(object.MyDate.substr(6)));

I've also seen this method:

var milli = "/Date(1245398693390)/".replace(/\/Date\((-?\d+)\)\//, '$1');
var d = new Date(parseInt(milli));

Convert string(Date(1646764200000+0530)) to date in the format(dd-mm-yyyy) using javascript

Converting to the DD-MM-YYYY requires formatting.

Here is one way to extract the date portion using the slice() method then formatting the output to your desired format. This assumes that the input date is always in the same form and length.

let dob = /Date(1646764200000+0530)/;

let date = new Date(+(""+dob).slice(6,19)).toLocaleString('en-GB',{year:"numeric",day:"2-digit",month:"2-digit"}).split("/").join("-");

console.log(date)

Convert .NET DateTimeFormatInfo to Javascript jQuery formatDate?

If only ShortDatePattern must be converted, the following code provides what I need:

public class wxDateTimeConvert
{
/// <summary>
/// Gets the javascript short date pattern.
/// </summary>
/// <param name="dateTimeFormat">The date time format.</param>
/// <returns></returns>
public static string GetJavascriptShortDatePattern(DateTimeFormatInfo dateTimeFormat)
{
return dateTimeFormat.ShortDatePattern
.Replace("M", "m")
.Replace("yy", "y");
}
}

Including Javascript in page:

    /// <summary>
/// Inserts the localized datepicker jquery code
/// </summary>
private void InsertLocalizedDatepickerScript()
{

string dateformat = wxDateTimeConvert.GetJavascriptShortDatePattern(Thread.CurrentThread.CurrentUICulture.DateTimeFormat);
String js = @"$(document).ready(function() {
$("".datepicker"").datepicker({
changeYear: true,
dateFormat: '" + dateformat + @"',
maxDate: new Date()
});
});";
this.Page.Header.Controls.Add(
new LiteralControl("<script type=\"text/javascript\">" + js + "</script>")
);
}

However, this does not handle month or day names, time formatting or other special cases.

Convert timestamp to a specific date format in javascript

How you can convert /Date(1231110000000)/ to DD/MM/YYYY format :

function convert(timestamp) {  var date = new Date(                          // Convert to date    parseInt(                                   // Convert to integer      timestamp.split("(")[1]                   // Take only the part right of the "("    )  );  return [    ("0" + date.getDate()).slice(-2),           // Get day and pad it with zeroes    ("0" + (date.getMonth()+1)).slice(-2),      // Get month and pad it with zeroes    date.getFullYear()                          // Get full year  ].join('/');                                  // Glue the pieces together}

console.log(convert("/Date(1231110000000)/"));

Javascript/jquery converting string to datetime (using New date in javascript) to pass to .net MVC

If you're certain that will be the entered date format, you could do something like this. All it's doing is reversing the month/day prior to creating the new Date object.

var dateOut = $(".txtOut").val().split("/");
var dateToSend = new Date(dateOut[1] + "/" + dateOut[0] + "/" + dateOut[2]);


Related Topics



Leave a reply



Submit