Convert date from json to regular format in jquery mobile - javascript

I got from json with date, date format is "2011-03-13T11:30:00Z" , and I want to convert it into normal format .
var Date= "Sunday, March 13th, 2011 " and var Time = "11:30"
i want to make it separate as above with proper format.
please help me....

Create a new Date object with the date string from the json data and then use the objects methods to get the date formats you want
var dateObject = new Date("2011-03-13T11:30:00Z");
var time = dateObject.getHours() + ':' + dateObject.getMinutes();
You also have the following which you could use to construct your date
dateObject.getDay(); // would return 0 for Sunday (days run 0-6 starting at Sun)
dateObject.getMonth(); // would return 2 for March (months run 0-11)
dateObject.getFullYear(); // return 2011
As per comments, to correct this for timezones, you need to know that the Z in your string denotes UTC/GMT, so if you are not in that timezone you need to correct for your difference to UTC
For example, replace the Z with +05:30 for being 5.5 hours ahead of UTC
var dateString = "2011-03-13T11:30:00Z".replace('Z', '+05:30');
var dateObject = new Date(dateString);

Related

new Date("YYYY/MM") not work on IE 11

In my project, i use js code below to take date with date input only year and month:
var current_time = new Date(current);
with current data is something like this: "2017/04"
It work perfect on chrome but on IE 11, i get invalid date for current_time. Can your guys help to to take date form data which only has year and month like this on IE? Thankyou.
Dates should be formatted according RFC 2822 or ISO 8601 So if you use '-' instead of '/ it will work every where.
console.log(new Date("2017-04"))
if you want to still have your date with '/' you can do this
console.log(new Date("2017/04".replace(/\//g, "-")));
The format you are using is not a standard format of date. Non standard date formats cause problems on various browsers like IE, safari, etc.
Use this method. It will work on all IE as well
Run it on chrome and IE. Here in this snippet, it will give one month less since stack snippet is using a different library for date parsing.
var input = "2017/04"
var year = input.split("/")[0]
// indexing starts with 0
var month = parseInt(input.split("/")[1],10) -1
var date = new Date(year,month)
console.log(date)
This is what it will output on browsers including IE
Sat Apr 01 2017 00:00:00 GMT+0530 (India Standard Time)
In order to create the date by passing the month and year to dateObject you can do:
current = '2017/04';
current = current.split("/")
var date = new Date(current[0], current[1]);
// it will return the date object where date is set as the first day of the month
console.log(date)
which will give you the date object set to the first day of the month.
If you want to get the current month and year you can do:
var year = new Date().getFullYear();
var month = new Date().getMonth() + 1;
date = year + '/' + month;
console.log(date);

JS: Convert Today's Date to ISOString() with Fixed Time

I'm trying to convert today's date to an ISO standard string but with the fixed time of T00:00:00.000Z.
I can get as far as returning a ISO string of today's date and time:
var isoDate = new Date().toISOString();
// returns "2015-10-27T22:36:19.704Z"
But I wanted to know if it's possible to have a fixed time, so it should return:
"2015-10-27T00:00:00.000Z"
Is this possible?
Any help is appreciated. Thanks in advance!
To get the current UTC date at midnight:
var d = new Date();
d.setUTCHours(0);
d.setUTCMinutes(0);
d.setUTCSeconds(0);
d.setUTCMilliseconds(0);
var output = d.toISOString();
To get the current local date, with the time portion set to UTC midnight:
var d = new Date();
var ts = Date.UTC(d.getFullYear(), d.getMonth(), d.getDate());
var output = new Date(ts).toISOString();
As for which to use, think through your requirements very carefully, The current UTC date and the local date may indeed be two different days.
For example, when it's midnight (00:00) October 27th in UTC, it's 8:00 PM on October 26th in New York.
Also, consider using moment.js, which makes operations like either of these much easier with the startOf('day') and .utc() functions.

JavaScript Date / Time

I have the following input and i can change the source of this data
Input
var strDate = "/Date(1391402871117+0100)/";
I can convert it to a date using eval, but i really dont want to eval
var DateResult1 = eval ("new Date(1391402871117+0100)");
console.log(DateResult1); // Date {Mon Feb 03 2014 05:47:51 GMT+0100 (Romance Standard Time)}
I did try this, sadly do not work:
// Remove /Date( )/
strDate = strDate.replace(/[^\d+]/g,'');
var DateResult3 = new Date(strDate);
console.log(DateResult3); //Date {Invalid Date}
When i write result of strDate i manual with out " it work.
var DateResult2 = new Date(1391402871117+0100);
console.log(DateResult2); // Date {Mon Feb 03 2014 05:47:51 GMT+0100 (Romance Standard Time)}
How can convert the input data into a date with out using eval or any library?
You are very likely not getting a correct result out of this code:
var DateResult2 = new Date(1391402871117+0100);
The problem is the addition: 1391402871117+0100. 0100 is an octal constant, equal to 64 in decimal, which would add 64 milliseconds to the 1391402871117 timestamp. It seems likely to be indended as a time zone instead, but the Date constructor does not support time zones — only UTC and the local time zone of the browser.
Since UNIX timestamps are actually absolute (they are always in UTC), using just the timestamp would result in a Date instance referencing the correct instant in time, but possibly at another time zone. You can disregard the +0100 part, by converting the "1391402871117+0100" into an integer using parseInt:
strDate = strDate.replace(/[^\d+]/g,'');
var DateResult2 = new Date(parseInt(strDate));
If you can change the data source, as you say, why not do this?
Have your data source generate something like this, to add the timezone offset to the timestamp:
// convert timezone offset hours into seconds and add them to the timestamp
return (unixTimestamp + (timezoneOffsetHours * 3600));
Then you can do something like this in your JS:
// Math.floor works faster than parseInt to convert a string to integer :)
var timestamp = Math.floor(result of above timestamp generation);
var DateResult = new Date(timestamp);
The reason:
new Date() can't handle timezones specified in this way (or at all as far as I can Google)
try by parsing string to int:
var strDate = "/Date(1391402871117+0100)/";
strDate = strDate.replace(/[^\d+]/g, '');
var DateResult3 = new Date(parseInt(strDate.split('+')[0]) + parseInt(strDate.split('+')[1]));
console.log(DateResult3);
Here is Demo

how to compare date which is given by user to date in javascript..?

In my web-site I am getting a date from user which in format like "dd-mm-yyyy",now I want to get the date which is 7-day before of that user's date.
I am able to get the current date in format "dd-mm-yyyy" but how would I know the date which is one week before user's date in javascript?
If you already have a Date object, use yourDate.setDate(yourDate.getDate() - 7 );
Try this--
var MyDate = new Date('11/30/2012'); //date format in mm/dd/yyyy
MyDate.setDate(MyDate.getDate() -7)
var newDate = MyDate.getMonth()+1 + '/' + MyDate.getDate() + '/' + MyDate.getFullYear()
alert(newDate);
Note- subtracting seven days to a date shifts the month or year and the changes are handled automatically by the Date object.
Why don't you use datejs, it's the best date related js library I have seen. Chcek the documentation here.
http://code.google.com/p/datejs/wiki/APIDocumentation
Search for add method
Set Dates
We can easily manipulate the date by using the methods available for the Date object.
In the example below we set a Date object to a specific date (14th January 2010):
var myDate=new Date();
myDate.setFullYear(2010,0,14);
And in the following example we set a Date object to be 7 days in past:
var myDate=new Date(); //or users date
// myDate will be users current date
myDate.setDate(myDate.getDate()-7);
//now substract 7 days to get the date u want.
Follow the following link
http://www.w3schools.com/js/js_obj_date.asp
Or follow this
http://www.techrepublic.com/article/manipulate-time-and-date-values-with-javascripts-date-object/6076869
You can convert a date string in the format dd-mm-yyyy to a date object using:
function toDate(d) {
d = d.split('-');
return new Date(d[2], --d[1], d[0]);
}
Then use Osiris' answer to add or subtract 7 days.

Convert (YYYY/MM/DD HH:MM:SS.MS) GMT to local time using JavaScript

For some reason, the SOAP response from one of my WebService looks like this:
2010/07/08 04:21:24.477
Where the date format is YYYY/MM/DD and the time is GMT.
I'm not really sure how to convert this to local time because the format is so odd.
Date.parse should actually parse most of the date string into its respective timestamp.
The 2 caveats appear to be:
Milliseconds aren't supported, so they have to be separated and added after parsing.
It'll assume local time, so 'GMT' or 'UTC' should to be appended before parsing.
With these in mind, the following should work:
function parseSoapDate(dateString) {
var dateParts = dateString.split('.'),
dateParse = dateParts[0],
dateMilli = dateParts[1];
return new Date(
Date.parse(dateParse + ' GMT') +
parseInt(dateMilli, 10)
);
}
var date = parseSoapDate('2010/07/08 04:21:24.477');
As for UTC to local time, JavaScript's Date objects should already handle that for you as they can report the date in both UTC and the user's local timezone. You specify which you want by the name of the method (whether it has UTC in it or not):
alert(date.toString()); // local time
alert(date.toUTCString()); // UTC time
This should work:
var dateStr = "2010/07/08 04:21:24.477";
var d = new Date(dateStr.split('.')[0]);
d.setUTCHours(0);
my JSON returns: YYYY-MM-DD HH:MM:SS, localization will work only on selected browsers Date.prototype.toLocaleDataString("en-us"[,option] )
function stringToDate(s) {
var language = window.navigator.userLanguage || window.navigator.language;
var options = {year: "numeric", month: "numeric", day: "numeric"};
s = s.split(/[-: ]/);
d = new Date(Date.UTC(s[0], s[1]-1, s[2], s[3], s[4], s[5]));
return d.toLocaleDateString( language , options)+" "+d.toLocaleTimeString();
}
// return
// Friday, November 15, 2013 2:21:04 PM --> FF25
// 11/15/2013 2:21:04 PM --> Chrome31
It looks like the response of the date/time is in ISO format, which is a sensible way to provide date information.
Suppose that the date returned is 7-8-2010. Would this be the 8th of July or the 7th of August? Having the date in ISO format (YYYY/MM/DD) solves this ambiguity.
You can convert this date to the required format in many different ways, i.e.
var input = '2010/07/08 04:21:24.477';
var now = new Date(input.slice(0, input.indexOf('.')));
alert(now.toLocaleString());
You may want to search the Internet for the Date object or to find snippets which will allow you to convert a date using many different formats.

Categories