Parse string as DateTime in Javascript from JSON - javascript

I want send a datetime in JSON with string fromat from asp.net web service and I want javascript parse it like datetime and not like string.
So I ask is there a special format that I must use it to convert datetime to string and parse it in javascript as datetime?
In fact , I don't want touch javascript. I want javascript read the string and considerate it as DateTime.

Make sure your date strings conform rfc2822 and use javascript Date.parse method.
Alternatively, send your dates over as integer milliseconds and use Date constructors on the javascript side.

I used DateJS for a few projects using ASP.NET. The format will probably depend on your locale. I would looks at the data.js examples to make it work the way it would fit your specification and locale.

This is a piece of code I use to create a date from a .net JSON serialized DateTime object.
function formatJSONDate(jsonDate) {
var d = new Date((jsonDate.slice(6, -2)*1));
var day = d.getDate() * 1;
var month = (d.getMonth() * 1) +1;
var s = (day < 10 ? "0" : "") + day + "-" + (month < 10 ? "0" : "") + month + "-" + d.getFullYear();
return s;
}

Related

Date format for Spanish speakers - returning NaN or Invalid Date [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
I have an Angular application
Goal: I want a user to be able to type in Spanish format for a date (DD/MM/YYYY). It should display in Spanish format to the user, but convert it back to English behind-the-scenes when sending the data to the Database
Problem: If they type something larger than 12 for the first 2 digits, then JavaScript Date complains that it's NaN.
What I tried: I looked up documentation and found the method toLocaleDateString and toLocaleString. However this is used on a Date. And if a date becomes NaN then I don't see how the method would work? I tried it out anyways but it just says Invalid Date {}
I am in central time zone if it matters.
TypeScript:
dateEnter(data) {
let dateSpanish = new Date(data).toLocaleDateString;
let dobForDB = (this.localeId == "es") ? this.myMethod(new Date(dateSpanish) : data;
}
myMethod(date: any) {
let year = date.getFullYear();
let day = date.getDate();
let month = date.getMonth() + 1;
let dateString = (this.localeId == "es") ? day.toString() + "/" + month.toString() + "/" + year.toString().substring(0, 4) : month.toString() + "/" + day.toString() + "/" + year.toString().substring(0, 4);
return dateString;
}
Consider using Moment.js for this scenario. It can detect the user's locale settings. Use the L format specifier to work with the short date for the locale.
moment("01/02/2019", "L").format("YYYY-MM-DD")
// Output in en-US: "2019-01-02" (January 2nd)
// Output in es-MX: "2019-02-01" (February 1st)
Keep in mind that it's not just language that determines the format. There are plenty of English-speaking locales that use DD/MM/YYYY formats. The United Kingdom is one example. It's primarily the United States (en-US) that use MM/DD/YYYY. see Date Format by Country on Wikipedia.

Remove 1 week from a date and keep the format

How can I remove 1 week from a date with JS without altering the date format (YYYY-MM-DD).
I saw several exemple but with the current date.
What I tried:
actual = '2017-04-10';
actual.setDate(actual.getDate() - 7);
Thanks.
You need to convert your string to a Date first.
Then, to get the format YYYY-MM-DD you can use .toISOString() and keep only the first 10 characters:
var d = new Date('2017-04-10'); // convert string to Date
d.setDate(d.getDate() - 7); // remove 7 days
var str = d.toISOString().slice(0, 10); // format YYYY-MM-DD
console.log(str);
Your date needs to be a date object:
actual = new Date('2017-04-10');
actual.setDate(actual.getDate() - 7);
The format is dictated by your operating system's regional settings and the format method you call on your date:
// You first need to turn your string into an actual JavaScript date:
actual = new Date('2017-04-10');
// Then you can use the Date API to modify it:
actual.setDate(actual.getDate() - 7);
// But the formatting of the date is determined by your operating system
// regional settings and the Date formatting method you call as well as
// how you, yourself decide to build your own custom format:
console.log(actual);
console.log(actual.toLocaleTimeString());
console.log(actual.toLocaleDateString());
console.log(actual.toISOString());
console.log(actual.getFullYear() + "-" + (actual.getMonth() + 1) + "-" + actual.getDate());

How to Convert date string to json date format in javascript?

In my application I am getting date in a string format like :
var date="1988-11-4".
I am calling back the WCF service and sending data to the service as Json format. But my problem is the WCF service is only accepting the dates as {DoB:"/Date(570931200000+0530)/"} format.
can you please tell how do I convert date to json date format like:
var jasonDate="/Date(570931200000+0530)/". Where 570931200000 is the miliseconds calculated since from "1970-01-01" and +0530 is the Timezone.
As a best guess, and to give you something to work with, until you understand what the relationship is and come back and explain things better along with what you have tried and the precise nature of the problem with your code.
var dateTime = '1988-05-03',
parts = dateTime.split('-'),
date;
parts[1] -= 1;
date = new Date(Date.UTC.apply(null, parts));
document.body.textContent = '/Date(' + date.getTime() + '-0000)/';
This might work:
var jsonDate = new Date(date).toJSON();
As the initial variable is only a string it would not be recognised as a date so create a date from it then convert that to JSON.
Thank you all for your response. I have got solution to my query. Here in the string "/Date(1208559600000-0700)/" 1208559600000 is the milliseconds calculated since from Jan 01 1970 and -700 is the time zone.
This the code that worked for me:
convertToJsonDate: function (date) {
var diff = date.getTime();
var jsonDate = "\/Date(" + diff + "-0700)\/";
return jsonDate;
},

Parse JSON (ISO8601) date string

I can create a JavaScript date object with:
var d=new Date('2012-08-07T07:47:46Z');
document.write(d);
This will write the date using the browser's time zone. But I should be able to do (no 'Z'):
var d=new Date('2012-08-07T07:47:46');
document.write(d);
This returns the same as above, but according to the ISO8601 standard, a string without a timezone (e.g. +01:00) and without 'Z', the date should be considered in the local time zone. So the second example above should write the datetime as 7:47am.
I am getting a datetime string from a server and I want to display exactly that datetime. Any ideas?
I found this script works well. It extends the Date.parse method.
https://github.com/csnover/js-iso8601/
Date.parse('2012-08-07T07:47:46');
It doesn't work on the new Date() constructor however.
You are right, Javascript doesn't play well with the ISO8601.
Use this function to convert to the desired format:
function ISODateString(d) {
function pad(n){
return n<10 ? '0'+n : n
}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var d = new Date();
print(ISODateString(d));
Taken from: Mozilla

How to format JSON date?

so, i need format JSON date from this format
"9/30/2010 12:00:00 AM", it is MM/DD/YYYY HH:MM:SS to format like this : DD/MM/YYYY, so i dont need info about hours, min and sec, and i need replace months and days from json, i tried some different ways but it always failed
i need do this using jQuery
also i didnt find any answer to formating this date type, all i found was formating date like this :/Date(1224043200000)/
so anyone have idea?
you can create a Date Object from a string like so:
var myDate = new Date(dateString);
then you can manipulate it anyway you want, one way to get your desired output is:
var output = myDate.getDate() + "\\" + (myDate.getMonth()+1) + "\\" + myDate.getFullYear();
you can find more at this elated.com article "working with dates"
Unfortunately your "from" dateformat is not the one which is implementation-independent in JavaScript. And all the other formats depends on the implementation, which means even if this format would be understood by most of the implementation I/you can't be sure for example how the DD and MM order would be parsed (I am almost sure it would be local regional settings dependent). So I would recommend to use a 3rd party (or your hand written) date parser to get a Date object out of your input string. One such parser you can find here:
http://www.mattkruse.com/javascript/date/
Because your question is not 100% clear for me, it's possible that you have your date in the format of /Date(number)/ which suggests that you are calling an ASP.Net service from your jQuery code. In this case during the JSON parse you can convert it to a Date object:
data = JSON.parse(data, function (key, value) {
// parsing MS serialized DateTime strings
if (key == '[NAME_OF_DATE_PROPERTY_IN_THE_JSON_STRING]') {
return new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
// maybe new Date(parseInt(value.substr(6))) also works and it's simpler
}
return value;
});
The code below solved my problem:
var date = new Date(parseInt(d.data[i].dtOrderDate.replace("/Date(", "").replace(")/", ""), 10));
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
Try something like this :
var date = new Date(parseInt(jsonDate.substr(6)));
where jsonDate is variable that stores your date

Categories