separate year from date object in JAVASCRIPT - javascript

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.

Related

The beginning of the year of the set date?

How can I find the beginning of the year for a set date? That is, let's say I set the date 2018-07-28, then the result should be 2018-01-01. I know that for example in Rails there is such a function as beginning_of_year.
Is there anything similar for nodejs?
Or maybe someone already has a similar for javascript?
You could use getFullYear and construct a new Date object
function beginning_of_year(date) {
return new Date(date.getFullYear(), 0);
}
beginning_of_year(new Date()); // Wed Jan 01 2020 00:00:00
First, Get the year from date and concatenation of string "01-01". Please check below :
new Date('2018-07-28').getFullYear()+'-01-01'
But if you wants to create Date object for year begging day. Please check below :
new Date(new Date('2018-07-28').getFullYear(), 0, 1)
You can do with the help of moment library .
var thisYear = (new Date()).getFullYear();
var start = new Date("1/1/" + thisYear);
var defaultStart = moment(start.valueOf());
It is easy way and also a efficient way .

How to get correct month using getMonth in javascript [duplicate]

This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
I have this
let d = new Date("03-08-2018"); //dd-mm-yyyy
console.log(d.getMonth()); // returns 02, I want 07
I have my date in dd-mm-yy. The getMonth() thinks I'm using mm-dd-yy.
How do I get correct month and date.
Your date format is not standard, and I strongly recommend not to use such code on a client web code, because how it behaves would be client-dependent.
EDIT (thx RobG) : Don't use the builtin parser new Date(), this will get you into trouble depending on the client timezone, even if you use a proper format where the month seems to be correctly recognized.
You'll have to create some function to parse the string yourself and create a Date object with year, month and day manually set, that would be the safe way.
Example of manual parsing :
let regex = /^(\d{2})-(\d{2})-(\d{4})$/; // each parsing group is day-month-year
let date = '03-05-2018';
let match = regex.exec(date);
let month = +match[2] - 1; // starting at 0, remove -1 if you want 1-based month number
console.log(month); // returns 4 in this example '03-05-2018'
(of course you should also put some guards if the string is not matching the correct format)
JS Date give the month starts with 0. So Try this below for getting month from date
let d = new Date("03-05-2018"); //dd-mm-yyyy
console.log(d.getMonth()+1);
if you want 4, then you should add +2 ( but i am not sure why you want 4)
let d = new Date("03-05-2018"); //dd-mm-yyyy
console.log(d.getMonth()+2);

Apply class to a column after date comparison in AngularJS + JavaScript

Following is the type of date I am getting from db - 2015-07-15T18:30:00.000Z . Now I am trying to add bootstap class btn-info if this date is 1 year before current date (Date.now()), if its less than or equals to 1 year but less than 3 months from current date then add class btn-warning, for 3 months or less add class btn-danger.
For this I am using ng-class on my field, like -
ng-class="calDateDiff(exp_date)"
In calDateDiff() method, I am trying to do the conversion, but unable to know which type of date format its represents.
I checked UTC in Js but its not that, also I tried Date.parse(Date.now()) but unable to know the format.
$scope.calDatediff = function(exp_date) {
// exp_date - Date.now()
// Here in calculation I am also not sure
// to handle leap years
}
Please let me know what type of date format is this and what is the right approach to handle this.
FYI- I don't want to use Moment.js as this is to be applied for only one column field, so it will be overhead just for one column to show.
EDIT 1 -
Ok I got this as its an ISO string -
so for current date I believe its going to be -
current date - new Date().toISOString()
let me know how I cam going to compare these two strings for an year, or 3 month condition ?
You can create a new date object and subtract.
Date.now() - new Date('2015-07-15T18:30:00.000Z')
1557113984
if you want to know if a year has elapsed one way to do it is to increment the date you got from the database and see if it is less than the current date:
var dbDate = new Date('2015-07-15T18:30:00.000Z');
dbDate
Wed Jul 15 2015 11:30:00 GMT-0700 (PDT)
dbDate.setMonth(dbDate.getMonth() + 12);
1468607400000
dbDate
Fri Jul 15 2016 11:30:00 GMT-0700 (PDT)
dbDate < Date.now()
false
That seems to me like an ISOString date. All you need to do is create a new object of type Date by passing that string to the constructor:
var dbDate = new Date("2015-07-15T18:30:00.000Z");
This will give you a Date object with which you can work with and easily compare it to Date.now(); I think you can do the rest of it by yourself.
Here's more info about Date: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date

javascript date format using dateFormat String

I am working on Javascript dates, I have one date which is in the form of 20 Jun 13, I
need to convert it into a Date Object, I used Date.parse() which returns 1 June 2013.
var frmDt = '20 Jun 13';
alert(Date.parse(frmDt));
Which is the solution?
I found date handling in javascript made extremely easier by using momentJs, which allows you to construct moment objects that actually wrap native javascript Date objects in a very liberal way, passing in strings of many different formats and actually being able to get a date object, in a way that is way more reliable than Date.parse().
You can also pass in a date format string, so your case would be something like moment('20 Jun 13', 'DD MMM YY').
d3.js has very robust capabilities for parsing and formatting dates. See https://github.com/mbostock/d3/wiki/Time-Formatting.
I have taken the code posted in my comment and turned it into a function, made the jan,feb,mar case insensitie and the seperator character between day month year can be any character (as long is there is one). so any format dd mmm yy or dd/mmm/yy or d mmm yy will work:
function toDate(str){
var months={
"JAN":1,
"FEB":2,
//... other months
"JUN":6,
//... other months
"DEC":12
}
var r=/^(\d{1,2}).(\w{3}).(\d{2}$)/;
if(r.test(str)===false){
throw new Error("Invalid date string:"+str);
}
var replaceFunction=function(){
var years=parseInt(arguments[3],10);
var m=months[arguments[2].toUpperCase()];
if(typeof m==="undefined"){
throw new Error("Invalid month name:"+arguments[2]);
}
var days=arguments[1]
m=(m<9)?"0"+m:m;
days=(days.length===1)?days="0"+days:days;
years=(years>50)?years="19"+years:"20"+years;
return m+"/"+days+"/"+years;
};
return new Date(str.replace(r,replaceFunction));
}
console.log(toDate("20 Jun 13"));

How can I parse a specific date string in JavaScript?

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.

Categories