Home Asp.net Format JSON Date String To Local DataTime Object Using JavaScript

Format JSON Date String To Local DataTime Object Using JavaScript

11
0

Now here in this tutorial, I’ll explain how to format JSON date string and convert into a valid local datatime object using JavaScript with example code.

In my previous tutorials, I’d explained preview image before upload using jquery, how to set dropdownlist selected value using javascript, how to disable submit button once form submitted and other more cracking tutorials on Asp.net, JavaScript, jQuery here.

 

Sometimes it’s necessary to convert the returned JSON date string into a valid javascript object and display within a webpage. If you’re looking for the same, simply follow this tutorial.

If you’ve JSON date something like /Date(1414151600000)/, you most likely wants to convert it into a valid date to perform your other operations.

Format JSON Date String Using JavaScript Function

Following is the function that will help us to convert JSON string into date time object:

<script type=”text/javascript”>
function formatJSONDate(jsonDate) {
var newDate = new Date(parseInt(jsonDate.substr(6)));
return newDate = newDate.toLocaleFormat(‘%d-%b-%Y’);
}
</script>

Call it as:

var jsonDate = “/Date(1414151600000)/”;
alert(formatJSONDate(jsonDate));

In the above example, the substr function takes out the /Date( part and the parseInt function gets the integer and ignores the )/ at the end. The final resulting number is passed into the Date constructor.

HTML Markup – [.aspx]

Following is the complete HTML markup code that I’ve used for this demonstration to format json date:

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head id=”Head1″ runat=”server”>
<title>Format JSON Date String To Valid Local DataTime Object</title>
<script type=”text/javascript”>
var jsonDate = “/Date(1414151600000)/”;
alert(formatJSONDate(jsonDate));
function formatJSONDate(jsonDate) {
var newDate = new Date(parseInt(jsonDate.substr(6)));
return newDate = newDate.toLocaleFormat(‘%d-%b-%Y’);
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
</form>
</body>
</html>

Note: If you are already using jQuery UI Datepicker Widget in your project you can do it by following simple way:

<script src=”//code.jquery.com/jquery-1.10.2.js”></script>
<script src=”//code.jquery.com/ui/1.11.4/jquery-ui.js”></script>
<script type=”text/javascript”>
var jsonDate = “/Date(1414151600000)/”;
var newDate = $.datepicker.formatDate(“d MM, yy”, new Date(parseInt(jsonDate.substr(6))));
alert(newDate);
</script>

LEAVE A REPLY

Please enter your comment!
Please enter your name here
Captcha verification failed!
CAPTCHA user score failed. Please contact us!