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);
Related
I need one help.I am unable to compare the selected date with today's date using Angular.js or JavaScript.I am explaining my code below.
var today=new Date();
console.log('2 dates',today,$scope.date);
From the above console i am getting the output like below.
2 dates Fri Jun 03 2016 18:29:16 GMT+0530 (India Standard Time) 03-06-2016
if(today > new Date($scope.date.split("-").reverse().join(","))){
alert('Please select future delivery date');
}
Here i need suppose my selected date is 03-06-2016 and today's date is 03-06-2016 the alert prompt should not come.But in my case its not happening like this.This alert message is coming also if selected date is 03-06-2016. Here i need the alert message should come if selected date is more than today's date only.Please help me.
Months are zero-indexed when constructing Dates:
console.log(new Date(2016,06,03));
"2016-07-03T04:00:00.000Z" // you expected June, but got July.
Note also that that is set to midnight: any new Date() run during the same day will be greater than that value.
String manipulation of dates is risky and error-prone, which is why everyone's knee-jerking momentjs at you (it is in fact a very good library and worth using if you're doing much date manipulation).
At the least, you may want to consider using a less ambiguous date format in $scope.date, but if you're stuck with that, in this case, you need to subtract 1 from the month when constructing a Date from it:
// this sample code will only work correctly on June 3 2016 :)
var $scope = {
date: "03-06-2016", // I am assuming DD-MM-YYYY format here
tomorrow: "04-06-2016"
};
var today = new Date();
// test against today:
var dArr = $scope.date.split('-');
var testDate = new Date(dArr[2],dArr[1]-1,dArr[0]);
if (today > testDate) {
console.log("today is greater than testDate.");
/* Note that anytime during today will be greater than the zero
o'clock constructed from $scope.date. If what you really want
is to alert only on the following day, then add 1 to the day
of $scope.date when converting it to a Date(). */
}
// now test against tomorrow:
dArr = $scope.tomorrow.split('-');
testDate = new Date(dArr[2],dArr[1]-1,dArr[0]);
if (today < testDate) {
console.log("today is less than (tomorrow's) testDate.");
}
Don't compare JavaScript dates using native < or > operators; install and use moment.js - it will handle all the difficulties for you:
if(moment(new Date()).isAfter(moment($scope.date, "MM-DD-YYYY"), 'day')) { ...
Convert to timestamp to compare it:
$scope.date = '2016-06-01';
var currentDate = new Date().valueOf();
var date = new Date($scope.date).valueOf();
if (currentDate > date) {
// something
}
It you use multi timezone, please convert both to a timezone.
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.
I have an input on my webpage that I am able to set the date on by getting an ISO string and pulling out the first 10 characters.
date = new Date();
dateInput.value = date.toISOString().substr(0,10);
This works perfectly. My problem is that when I try to get the date back out. I am getting the date one day off.
var newDate = new Date(dateInput.value);
I have also tried the following code to make up for it, but it is not always correct either
new Date(Date.parse(element.value) + 86400000)
So my question is: Is there an elegant way to get the correct date consistently. I have been looking around for a little while, but it seems there is not a lot of consistency with date parsing in Javascript.
If it's an actual date input on a supporting browser, then it will have a valueAsDate property. There's no need to parse it.
It's interpreting the date as UTC, which, for most time zones, will make it seem like "yesterday". One solution could be to add the time-zone offset back into the date to "convert" it to your local timezone.
var newDate = new Date(dateInput.value + 'T00:00');
This will give the correct date in any timezone.
You can also convert the input string from YYYY-MM-DD to MM/DD/YYYY and it then parse the date to get the correct answer.
EXAMPLE:
Don't use:
new Date(Date.parse('2018-09-28')) // Thu Sep 27 2018 19:00:00 GMT-0500 (Central Daylight Time)
Rather use
new Date(Date.parse('09/28/2018')) // Fri Sep 28 2018 00:00:00 GMT-0500 (Central Daylight Time)
(NOTE: I am in CDT)
Tested in Chrome, Firefox, Safari, old Edge, and IE.
as said by Marty the problem is the difference between the representation of the timezone of the input (UTC defined by W3C) and the JS timezone (local). The solution is to getTimezoneOffset (which is in minutes) and convert everything to milliseconds:
var today = document.getElementById("myInputDate").valueAsDate;
var tomorrow = new Date(today.valueOf() + 86400000 + (today.getTimezoneOffset() * 60000));
86400000 = milliseconds of a day
today.getTimezoneOffset() * 60000 = timezoneOffset in milliseconds
Try using .toLocaleString to get the date into the input, and add the time when parsing it, like this:
date = new Date();
dateInput.value = date.toLocaleString("sv-SE", {
hour: "2-digit",
minute: "2-digit",
second: "2-digit"
});
And to get the value into a Date object use:
new Date(inputdateInput.value + "T00:00");
I wrote a little post about converting between Date objects and date inputs here
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);
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.