I get a date which comes in this format: ddmmyy, and I need to do some validation with it.
How can I parse it to a javascript date object?
I've tried to search, and there are a lot on the ddmmyyyy format, but not the format I get.
EDIT: Example date: 031290 = 3.12.1990.
You could parse ddmmyyyy into a yyyy-mm-dd form and pass that to Date.parse.
Date.parse( "02032002".replace(/^(\d\d)(\d\d)(\d{4})$/, "$3-$2-$1") );
Or otherwise split it up and use the Date's setters / constructor:
// month - 1 : in this form January is 0, December is 11
var date = new Date( year, month - 1, date );
Just noticed the YY vs YYYY part of the question:
var parts = /^(\d\d)(\d\d)(\d{2})$/.exec( "190304" );
var date = new Date( parts[3], parts[2]-1, parts[1] );
You could augment that with some code which adds a 20 or 19 depending if the year is over or below a certain threshold (like 70 : < 70 indicates 20xx and >= 70 indictaes 19xx years).
Try this:
var a="221178".split(/(?=(?:..)*$)/);
var result=new Date ( parseInt(a[2],10) + 1900 , a[1]-1 , a[0] )
result:
Tue Nov 22 1978 00:00:00 GMT+0200
JSBIN
If you want a non-regex solution, you can use new Date(year, month, date) constructor, and simple cut strings into those parts. It's not fancy, but it clear in what it does:
function parse2date(str){
var year = parseInt(str.substr(4, 2));
var month = parseInt(str.substr(2, 2));
var day = parseInt(str.substr(0, 2))
return new Date(year < 20 ? 2000 + year : year, month - 1, day)
}
this function assumes if 2-disgit years is below 20 - then it is meant to be in 2000s, otherwise it's in 1900s. But you can adjust the limit. Try calling it:
alert(parse2date('031290'));
Ok, so here is how I solved it.
The answers here is right, except I wasn't happy with the way the detection of the current century worked; so I basically did this:
var date = new Date(year + 2000, month - 1, day);
if (date > new Date())
date.setYear(year + 1900);
With this code, I can maximum validate an age of 100, but that shouldn't be a problem.
Mukul Goel in the comment below points out it can only validate dates in the future. Probably right, I haven't checked it myself.
Related
I'm trying to calculate a date based on another date by adding a certain period of time. Let's say if I want to add 3 months to a date, then the new date should be one day before the date after 3 months. Taking that example, below is the code that I came closest to for achieving what I want to do:
new Date(
date
.setMonth(date.getMonth() + 3)
.setDate(date.getDate() - 1)
)
But this returns an error: TypeError: date.setMonth(...).setDate is not a function. I think the chaining of methods is not working, so I'll probably have to setDate in the next statement. Is there a way to do this in a single statement of code?
Is there a way to set date and month on a date object in a single statement?
Yes. The following sets the month to January and the day to the first on one statement:
let d = new Date();
d.setMonth(0, 1);
…if I want to add 3 months to a date, then the new date should be one day before the date after 3 months
No, you can't do that in one statement because adding a month needs to consider the number of days in the month. E.g. adding one month to 31 Jan 2020 results in
31 Feb, and since there were only 29 days in Feb 2020, the date is set to 2 Mar 2020. Similarly, adding 1 month to 31 May gives 31 Jun which rolls over to 1 Jul. So you need to add months first (see Adding months to a Date in JavaScript), then subtract one day (see Add days to JavaScript Date).
You could extend the Date Object and create your own methods which are chainable.
class MyDate extends Date {
constructor() {
super(...arguments)
}
changeMonth(amount) {
return new MyDate(this.setMonth(this.getMonth() + amount));
}
changeDate(amount) {
return new MyDate(this.setDate(this.getDate() + amount));
}
};
const date = new MyDate();
console.log("Original:", date);
console.log("Changed :", date.changeMonth(3).changeDate(-5));
You could so something like
newDate = new Date(newDate.getFullYear(), newDate.getMonth() + 3, endDate.getDate() -1)
Turns out there is a very simple solution. The setMonth() method allows us to pass an optional dayValue parameter (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth). Using which, the code simply becomes:
new Date(
date.setMonth(
date.getMonth() + 3,
date.getDate() - 1
)
)
I am trying to subtract hours from a given date time string using javascript.
My code is like:
var cbTime = new Date();
cbTime = selectedTime.setHours(-5.5);
Where selectedTime is the given time (time that i pass as parameter).
So suppose selectedTime is Tue Sep 16 19:15:16 UTC+0530 2014
Ans I get is : 1410875116995
I want answer in datetime format.
Am I doing something wrong here? Or there is some other solution?
The reason is that setHours(), setMinutes(), etc, take an Integer as a parameter. From the docs:
...
The setMinutes() method sets the minutes for a specified date
according to local time.
...
Parameters:
An integer between 0 and 59, representing the minutes.
So, you could do this:
var selectedTime = new Date(),
cbTime = new Date();
cbTime.setHours(selectedTime.getHours() - 5);
cbTime.setMinutes(selectedTime.getMinutes() - 30);
document.write('cbTime: ' + cbTime);
document.write('<br>');
document.write('selectedTime: ' + selectedTime);
Well first off setting the hours to -5.5 is nonsensical, the code will truncate to an integer (-5) and then take that as "five hours before midnight", which is 7PM yesterday.
Second, setHours (and other functions like it) modify the Date object (try console.log(cbTime)) and return the timestamp (number of milliseconds since the epoch).
You should not rely on the output format of the browser converting the Date object to a string for you, and should instead use get*() functions to format it yourself.
According to this:
http://www.w3schools.com/jsref/jsref_sethours.asp
You'll get "Milliseconds between the date object and midnight January 1 1970" as a return value of setHours.
Perhaps you're looking for this:
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_sethours3
Edit:
If you want to subtract 5.5 hours, first you have to subtract 5 hours, then 30 minutes. Optionally you can convert 5.5 hours to 330 minutes and subtract them like this:
var d = new Date();
d.setMinutes(d.getMinutes() - 330);
document.getElementById("demo").innerHTML = d;
Use:
var cbTime = new Date();
cbTime.setHours(cbTime.getHours() - 5.5)
cbTime.toLocaleString();
try this:
var cbTime = new Date();
cbTime.setHours(cbTime.getHours() - 5.5)
cbTime.toLocaleString();
I'm trying to display a date with format "MMM. dd HH:mm:ss.nnn". It is rendering it incorrectly in IE and I have spent quite some time and I can't figure out why I can't get this to work.
I know that Date.UTC returns the number of miliseconds in a Date object since Jan 1, 1970. So,
var newDate = new Date(Date.UTC(year, month[, date[, hrs[, min[, sec[, ms]]]]])
newDate.toString("MMM. dd HH:mm:ss.")+row.timestamp.getMilliseconds();
will work.
Example:
var newDate = new Date(Date.UTC(1950, 10, 10, 10, 09, 09, 100));
row.timestamp_f = newDate.toString("MMM. dd HH:mm:ss."); // Output => Nov. 10 05:09:09.
But, I am interating this from a jquey.each function so the date string that I am working with is an ISO 8601: "2013-03-12T15:14:10.483". So, this is what I have in mind.
var numMilisecond = Date.parse(row.timestamp);
var newDate = new Date(numMilisecond);
row.timestamp_f = newDate.toString("MMM. dd HH:mm:ss."); // Output => Dec. 31 19:00:00.
row.timestamp is from a JSON response
{"timestamp":"2013-03-12T15:14:10.483" ...}
Why doesn't the code work? Date.parse should return the number of miliseconds since Jan 1, 1970 and then I create a new Date obj and then convert it to string just like the code in the first snipet. What am I doing wrong?
Thanks.
Date.toString shouldn't accept any arguments. If you want a true date-formatting solution, you'll need to use a plugin or roll your own.
var shortmonths = ['Jan','Feb','Mar','Apr',]; // remaining months are left as an exercise for the reader
row.timestamp_f = shortmonths[newDate.getMonth()]
+ ". "+newDate.getDate() + " "
+ newDate.toLocaleTimeString() + ".";
I have been using
timeStamp = new Date(unixTime*1000);
document.write(timeStamp.toString());
And it will output for example:
Tue Jul 6 08:47:00 CDT 2010
//24 hour time
Screen real estate is prime, so I would like to take up less space with the date and output:
mm/dd/yy hh:mm
//also 24 hour time
Just add an extra method to the Date object, so you can reuse it as much as you want. First, we need to define a helper function, String.padLeft:
String.prototype.padLeft = function (length, character) {
return new Array(length - this.length + 1).join(character || ' ') + this;
};
After this, we define Date.toFormattedString:
Date.prototype.toFormattedString = function () {
return [String(this.getMonth()+1).padLeft(2, '0'),
String(this.getDate()).padLeft(2, '0'),
String(this.getFullYear()).substr(2, 2)].join("/") + " " +
[String(this.getHours()).padLeft(2, '0'),
String(this.getMinutes()).padLeft(2, '0')].join(":");
};
Now you can simply use this method like any other method of the Date object:
var timeStamp = new Date(unixTime*1000);
document.write(timeStamp.toFormattedString());
But please bear in mind that this kind of formatting can be confusing. E.g., when issuing
new Date().toFormattedString()
the function returns 07/06/10 22:05 at the moment. For me, this is more like June 7th than July 6th.
EDIT: This only works if the year can be represented using a four-digit number. After December 31st, 9999, this will malfunction and you'll have to adjust the code.
How can I create a date object which is less than n number of months from another date object? I am looking for something like DateAdd().
Example:
var objCurrentDate = new Date();
Now using objCurrentDate, how can I create a Date object having a date which is six months older than today's date / objCurrentDate?
You can implement very easily an "addMonths" function:
function addMonths(date, months) {
date.setMonth(date.getMonth() + months);
return date;
}
addMonths(new Date(), -6); // six months before now
// Thu Apr 30 2009 01:22:46 GMT-0600
addMonths(new Date(), -12); // a year before now
// Thu Oct 30 2008 01:20:22 GMT-0600
EDIT: As reported by #Brien, there were several problems with the above approach. It wasn't handling correctly the dates where, for example, the original day in the input date is higher than the number of days in the target month.
Another thing I disliked is that the function was mutating the input Date object.
Here's a better implementation handling the edge cases of the end of months and this one doesn't cause any side-effects in the input date supplied:
const getDaysInMonth = (year, month) => new Date(year, month, 0).getDate()
const addMonths = (input, months) => {
const date = new Date(input)
date.setDate(1)
date.setMonth(date.getMonth() + months)
date.setDate(Math.min(input.getDate(), getDaysInMonth(date.getFullYear(), date.getMonth()+1)))
return date
}
console.log(addMonths(new Date('2020-01-31T00:00:00'), -6))
// "2019-07-31T06:00:00.000Z"
console.log(addMonths(new Date('2020-01-31T00:00:00'), 1))
// "2020-02-29T06:00:00.000Z"
console.log(addMonths(new Date('2020-05-31T00:00:00'), -6))
// "2019-11-30T06:00:00.000Z"
console.log(addMonths(new Date('2020-02-29T00:00:00'), -12))
// "2019-02-28T06:00:00.000Z"
Create date object and pass the value of n, where n is number(add/sub) of month.
var dateObj = new Date();
var requiredDate= dateObj.setMonth(dateObj.getMonth() - n);
var oldDate:Date = new Date();
/*
Check and adjust the date -
At the least, make sure that the getDate() returns a
valid date for the calculated month and year.
If it's not valid, change the date as per your needs.
You might want to reset it to 1st day of the month/last day of the month
or change the month and set it to 1st day of next month or whatever.
*/
if(oldDate.getMonth() < n)
oldDate.setFullYear(oldDate.getFullYear() - 1);
oldDate.setMonth((oldDate.getMonth() + n) % 12);
You have to be careful because dates have a lot of edge cases. For example, merely changing the month back by 6 doesn't account for the differing number of days in each month. For example, if you run a function like:
function addMonths(date, months) {
date.setMonth((date.getMonth() + months) % 12);
return date;
}
addMonths(new Date(2020, 7, 31), -6); //months are 0 based so 7 = August
The resulting date to return would be February 31st, 2020. You need to account for differences in the number of days in a month. Other answers have suggested this in various ways, by moving it to the first of the month, or the last of the month, or the first of the next month, etc. Another way to handle it is to keep the date if it is valid, or to move it to the end of the month if it overflows the month's regular dates. You could write this like:
function addMonths(date, months) {
var month = (date.getMonth() + months) % 12;
//create a new Date object that gets the last day of the desired month
var last = new Date(date.getFullYear(), month + 1, 0);
//compare dates and set appropriately
if (date.getDate() <= last.getDate()) {
date.setMonth(month);
}
else {
date.setMonth(month, last.getDate());
}
return date;
}
This at least ensures that the selected day won't "overflow" the month that it is being moved to. Finding the last day of the month with the datePart = 0 method is documented here.
This function still leaves a lot to be desired, as it doesn't add years and you can't subtract more than a year (or you will run into a new issue with negatives being involved). However, fixing those and the other issues you may run into (namely timezones) will be left as an exercise for the reader.