Let's say that I have date as a string, like: 02-12-2011
How can I parse it, and make it in format:
Friday, 02 December, 2011.
Thank you in advance!
Something like this should work:
var date = "02-12-2011".split('-');
var month = (date[0] * 1 ) - 1; // * 1 to convert to Number - 1 to subtract to 1 (months are from 0 - 11)
var day = date[1];
var year = data[2];
var d = new Date();
d.setMonth(month);
d.setDate(day);
d.setFullYear(year);
console.log(d.toDateString()); // will output Sat Feb 12 2011
You could also format the date differently by creating your own function that uses the getters getMonth(), getDate(), getFullYear(), getDay().
If you'd like a lighter weight solution. Otherwise the link that #diEcho mentions looks good.
Also, the W3School references, while not the best for style, are pretty decent for a general 'get to the facts' reference about the various JavaScript Objects.
Here's a link to the Date object: http://www.w3schools.com/jsref/jsref_obj_date.asp
This blog article on JavaScript date formatting will help on the formatting part.
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 sorry I might be flamed for this but as a newbie I would like to make this work it is on Dates. I have this code:
var date = new Date('Apr 21, 2015');
and when I alert using this code:
var date = new Date('Apr 21, 2015');
alert(date.getFullYear());
alert(date.getMonth());
alert(date.getDate ());
it displays NaN. Can someone suggest me how to do this?
The problem is here:
var date = new Date('Apr 21, 2015');
There's no support for that date/time format in the specification. If a particular JavaScript engine supports it, it's because it's going above and beyond, and you cannot count on it. So you end up with a Date instance with the "time value" NaN (the "time value" is the number of milliseconds since The Epoch — Jan 1 1970), and all of the various methods like getFullYear and such return NaN.
So:
If you need to parse that format, you'll have to write code to do it, or use a library like MomentJS or several others that have already been written.
If you just need to get that date as a Date instance, rather than using the string, you can build it from the multi-argument constructor:
var date = new Date(2015, 3, 21); // Months start at 0, so 3 = April
According to MDN. The constructor that accepts a string value only accepts IETF-compliant RFC 2822 timestamps and a version of ISO8601
This is the IETF RFC 2822
date-time = [ day-of-week "," ] date FWS time [CFWS]
day-of-week = ([FWS] day-name) / obs-day-of-week
day-name = "Mon" / "Tue" / "Wed" / "Thu" /
"Fri" / "Sat" / "Sun"
date = day month year
year = 4*DIGIT / obs-year
month = (FWS month-name FWS) / obs-month
month-name = "Jan" / "Feb" / "Mar" / "Apr" /
"May" / "Jun" / "Jul" / "Aug" /
"Sep" / "Oct" / "Nov" / "Dec"
day = ([FWS] 1*2DIGIT) / obs-day
time = time-of-day FWS zone
time-of-day = hour ":" minute [ ":" second ]
hour = 2DIGIT / obs-hour
minute = 2DIGIT / obs-minute
second = 2DIGIT / obs-second
zone = (( "+" / "-" ) 4DIGIT) / obs-zone
and the ECMA5.1 is
YYYY-MM-DDTHH:mm:ss.sssZ
YYYY
YYYY-MM
YYYY-MM-DD
Clearly your string 'Apr 21, 2015' does not fit any of the above formats so it does not work. As T.J. Crowder pointed out, if you are not using standard formats, it's very up to the engine whether or not your code works.
If you plug the following into jsfiddle, it works fine, fiving 2015, 3 and 21 (at least under FF and IE):
var date = new Date('Apr 21, 2015');
alert(date.getFullYear());
alert(date.getMonth());
alert(date.getDate ());
So your problem may well lie elsewhere. Your best bet would be to construct a complete (but as short as possible) sample that exhibits the problem, then show us that.
If that simple code does cause the problem in your environment (with minimal other code), it may be that it doesn't support that format of constructor. ECMAScript specifies that, for a one-argument constructor where the argument is a string, it's like calling Date.parse() on that string and setting the object's value to the equivalent time value.
However, it's only required to handle a simplified ISO8601 format along the lines of:
YYYY-MM-DDTHH:mm:ss.sssZ
not something more free format such as April 21, 2015.
If the constructor has two to seven arguments, it's of the form:
new Date (year,month[,date[,hours[,minutes[,seconds[,ms]]]]])
with the individual fields given separately.
Hence there is no requirement under the standard for a given implementation to accept what you've given. A good test would be to use:
var date = new Date(2015,3,21);
and see if that fixes it.
That also gives you the same results in jsfiddle as previously and it may also fix the problem in your specific environment as well.
If you need to be able to parse those date formats and you don't want to restrict yourself to environments that allow them, you may need to resort to a third-party library.
The Date-Function works as the fallowing:
new Date(year, month, day, hours, minutes, seconds, milliseconds)
So this should works for you:
var date = new Date(2015, 3, 21);
alert(date.getFullYear());
alert(date.getMonth());
alert(date.getDate ());
Try to this.
var today = new Date("Apr 21, 2015");
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = mm+'/'+dd+'/'+yyyy;
alert(today);
Your code works in jshint and js.do
The date string you use is not in proper ISO format, therefore the question if it works mainly depends on OS and browser locale environment settings.
Try to parse the string first and handover the result to the Date constructor like this:
var date = new Date(Date.parse('Apr 21, 2015'));
I have an issue regarding separate year from date object. I just came to know whenever I pass the String to the DATE object then my years is incremented by 1 or 2 .
for example.
var licenceStartDateConv = new Date(licenceStartDate);
var licenceStartDateYear = licenceStartDateConv.getUTCFullYear();
when i pass the licenceStartDate = "13/08/2011" then the function returns me licenceStartDateYear = Sun Jan 8 00:00:00 UTC+0500 2012 instead of 2011. why is it so?
can someone please sort out this issue ? I shall be very grateful to you people.
Thanks in Advance.
If you are using a "xx/yy/zzzz" format to supply a date string to the Date constructor, it will be parsed as "mm/dd/yyyy", as Ankit pointed out in the original question. You will have to parse the date string to pull the Day, Month and Year out and create a Date object using these.
For example:
// Parse the date using a regular expression.
var dateFields = /(\d\d)\/(\d\d)\/(\d{4})/.exec("13/08/2011");
licenceStartDateConv = new Date(dateFields[3], dateFields[2]-1, dateFields[1]); // -1 on month to account for offset.
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);
I have an HTML form where I am allowing users to enter a date to print out a report. However, if that date is within 3 days of the current date, I have it set to tell the user that they must wait 3 days. For some reason the code works when I enter something like "09/30/2012" but when I enter "10/01/2012", the error check skips. It seems at though, if it's a double digit month (10, 11, and 12), it complete skips the error check. Please let me know if you have any ideas. Thanks
JS Code:
var date = myForm.SC_date.value;
var d = new Date(date);
var varBegin = (d.getMonth()+1) + "-" + (d.getDate()-3) + "-" + d.getFullYear()
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if (myForm.SC_date.value == "")
window.alert("Please enter the requested date of variance. NOTE: Date must be 3 days prior to today's date.")
//Here is where I am having issues
/*else if(new Date(date) > new Date(varBegin))
window.alert("Invalid date. You must wait at least 3 days before you can request a report.")*/
else if(!myForm.SC_date.value.match(re))
window.alert("Invalid date. Please enter the date as follows: mm/dd/yyyy.")
HTML Code:
<td>Date of Variance </td>
<td colspan="2"><input name="SC_date:*" id="SC_date" type="text" tabindex="06">
</textarea><b><span class="style3">*</span> </b><span class="style2">(mm/dd/yyyy)</span>
</td>
I don't think you want to construct your "3 days ago" date by manipulating a string. I.e., this snippet here:
var varBegin = (d.getMonth()+1) + "-" + (d.getDate()-3) + "-" + d.getFullYear()
First, I'm not sure why you're using hyphens as delimiters here, when you are using forward-slashes as delimiters in your input field?
In any case, that's not a reliable way to construct the date. When you feed a string into the constructor of a Date object, you are effectively calling Date.parse(). That behaves differently on different browsers.
Check this out:
> new Date('1-1-2012');
Sun Jan 01 2012 00:00:00 GMT-0800 (PST)
> new Date('01-01-2012');
Sun Jan 01 2012 00:00:00 GMT-0800 (PST)
> new Date('2012-1-1');
Sun Jan 01 2012 00:00:00 GMT-0800 (PST)
Looks pretty good, right? But that's on Chrome.
Now check out what happens in an up-to-date version of Firefox, with the exact same calls:
> new Date('1-1-2012');
Date {Invalid Date}
> new Date('01-01-2012');
Date {Invalid Date}
> new Date('2012-1-1');
Date {Invalid Date}
> new Date('2012-01-01');
Date {Sat Dec 31 2011 16:00:00 GMT-0800 (PST)}
Furthermore, look at this behavior, in both browsers:
> new Date('2012-01-01');
Sat Dec 31 2011 16:00:00 GMT-0800 (PST)
Simply prepending zeroes to the month and date digits causes a time warp! You have to set the time and a timezone (for me, PST) to make that go away:
> new Date('2012-01-01T00:00:00-08:00')
Sun Jan 01 2012 00:00:00 GMT-0800 (PST)
Basically, dealing with date string parsing is a headache. You don't want to have to digest and account for specs like this, this, and this.
So, here's a better alternative -- pass the year, month, and date values (in that order) to the constructor of the Date object. That will reliably create the date for you, so your comparisons are valid.
Like this, for your specific example:
var WARNING_PERIOD_IN_DAYS = 3;
// Extract month, day, year from form input, 'trimming' whitespace.
var re = /^\s*(\d{1,2})\/(\d{1,2})\/(\d{4})\s*$/;
var match = re.exec(inputVal); // from "myForm.SC_date.value".
if (match) {
var month = parseInt(match[1]) - 1; // Zero-indexed months.
var date = parseInt(match[2]);
var year = parseInt(match[3]);
var inputDate = new Date(year, month, date);
var currentDate = new Date();
var threeDaysAgo = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDay() - WARNING_PERIOD_IN_DAYS);
console.log((inputDate > threeDaysAgo) ? 'Within warning period' : 'No warning needed');
}
Speaking of specs, there's one cool thing to note here, which is that in JavaScript, you can "wrap" the date value (it can be too large, or negative), and the resulting Date will still be valid and correct. Here's why:
From the ECMAScript 262 spec, here's what happens when you call setDate():
**15.9.5.36 Date.prototype.setDate (date)**
1. Let t be the result of LocalTime(this time value).
2. Let dt be ToNumber(date).
3. Let newDate be MakeDate(MakeDay(YearFromTime(t), MonthFromTime(t), dt), TimeWithinDay(t)).
4. Let u be TimeClip(UTC(newDate)).
5. Set the [[PrimitiveValue]] internal property of this Date object to u.
6. Return u.
This is the key bit: MakeDay(YearFromTime(t), MonthFromTime(t), dt)
MakeDay gets the year and the month from the current time value of the Date object (in milliseconds of epoch time), and does this:
**15.9.1.12 MakeDay (year, month, date)**
The operator MakeDay calculates a number of days from its three arguments, which must be ECMAScript Number values. This operator functions as follows:
1. If year is not finite or month is not finite or date is not finite, return NaN.
2. Let y be ToInteger(year).
3. Let m be ToInteger(month).
4. Let dt be ToInteger(date).
5. Let ym be y + floor(m /12).
6. Let mn be m modulo 12.
7. Find a value t such that YearFromTime(t) == ym and MonthFromTime(t) == mn and DateFromTime(t) == 1;
but if this is not possible (because some argument is out of range), return NaN.
8. Return Day(t) + dt - 1.
This looks rather involved, but basically it's:
The floor, modulo, and date==1 bits handle month rollovers (months that are negative or greater than 12).
The resulting instant in epoch time is converted to a number of days.
Your date value is added to that number of days. If your date value is negative, that's fine, it will just be subtracted.
The result is passed back to setDate().
setDate calls MakeDate(), which converts the number of days plus the intra-day time into milliseconds in epoch time.
The Date object's internal time is set to this new epoch time.
That's why you can do stuff like this (comments taken from the MakeDay() function in the V8 JS engine project):
// MakeDay(2007, -4, 20) --> MakeDay(2006, 8, 20)
// MakeDay(2007, -33, 1) --> MakeDay(2004, 3, 1)
// MakeDay(2007, 14, -50) --> MakeDay(2007, 8, 11)
Ok, so that was almost certainly too much detail for this particular problem... but I just wanted to make clear what's really going on behind the scenes. Thanks for your patience.
And... just one last thing...
You have a random </textarea> hanging out in that HTML snippet. If there is an opening <textarea> somewhere before it, then it's incorrectly enclosing some of your other elements. If there is no opening <textarea>, then delete it.
If you don't care about the time of the day, I recommend you do the following:
var dUser = new Date(date); //just like you did before
var dVarBegin = new Date("10/05/2012"); //here you do whatever is the date you are setting.
var diff = dVarBegin.getTime() - dUser.getTime();
//now diff is the difference in milliseconds!
I don't fully understand your requirements in relation to the 3 days. However, if what you needed was to compare dates, now you can! I hope this works for you. If you need something more, please ellaborate a little bit on the 3 days thing.
Use a library that lets you control the date formats accepted, e.g. Globalize.js or Date.js. Then define the exact test you wish to carry out especially whether time of the day is significant and whether the test should be relative to current time in user’s system (which is what you get with new Date() without arguments). You can then e.g. calculate a time difference as outlined by #Mamsaac and convert milliseconds to days with simple arithmetic.
It is illogical to use Date() and then, without checking the result, start doing pattern matching on the input. Moreover, Date() is by definition system-dependent and should seldom be used. There is no guarantee that it will accept a format like mm/dd/yyyy at all.