how to get getUTCDate() and getUTCMonth() with 0 ?
my code is
var d = new Date();
var day = d.getUTCDate();
var month = d.getUTCMonth()+1;
var year = d.getUTCFullYear();
If Today date is 1-1-2015 than i want to day=01 instead of 1 and month=01 instead of 1;
There's no built-in shortcut for doing that. You just put a 0 in front of it if necessary:
var month = String(d.getUTCMonth());
if (month.length === 1) {
month = "0" + month;
}
Or use a date/time library like MomentJS which features formatting functions.
On modern browsers, you can also dice up the string toISOString gives you, as it's always in UTC:
var parts = d.toISOString().substring(0, 10).split("-");
var day = parts[2];
var month = parts[1];
var year = parts[0];
Related
I need date algorithms, Which will display me how long I have been given a date anywhere.
Example:
Suppose
Today is 01/06/2019 (dd/mm/yy)
BirthDate is 31/05/2019 (dd/mm/yy)
Now, My age is 1 day 0 Months and 0 years
[NOTE: I need all of them, It means day/month and years]
I have been read at least 23 articles/post in this site but they only give years or month or date but not everything in one...
var date, cDate, cMonth, cYears, oDate, oMonth, oYears;
date = new Date()
//current date
cDate = date.getDate()
cMonth = date.getMonth()
cYears = date.getFullYear()
//birth date
oDate = 01
oMonth = 05
oYears = 2019
(Multiplying is not the main solution I think so, need to work with all arithmetics operator)
This will give you the result you need
var birth = new Date("5/31/2019"); // mm/dd/year
var today = new Date();
var diff = today.valueOf()-birth.valueOf();
var result = new Date(diff);
var dayDiff = result.getDate() - 1; //because epoch start from 1st
var yearDiff = result.getFullYear() - 1970; //because epoch start from 1970
var str = `${dayDiff} day ${result.getMonth()} Months and ${yearDiff} years`;
console.log(str);
You should use moment, so there you can do:
var a = moment("04/09/2019 15:00:00");
var b = moment("04/09/2013 14:20:30");
console.log(a.diff(b, 'years'))
console.log(a.diff(b, 'months'))
console.log(a.diff(b, 'days'))
Similarly, you can get minutes, hours and seconds if you need.
While using the library moment.js
This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 4 years ago.
I want to the current date/time formatted in this format:
year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second+':'+milli;
Currently I'm doing it as such. Is there a more elegant approach without the use of external libraries like moment.js?
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var milli = now.getMilliseconds();
if(month.toString().length == 1) {
var month = '0'+month;
}
if(day.toString().length == 1) {
var day = '0'+day;
}
if(hour.toString().length == 1) {
var hour = '0'+hour;
}
if(minute.toString().length == 1) {
var minute = '0'+minute;
}
if(second.toString().length == 1) {
var second = '0'+second;
}
if(milli.toString().length == 1) {
var milli = '0'+milli;
}
var m_session_startTime = year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second+':'+milli;
Leverage template literals instead of concatenation and padStart() to fill leading zeros.
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, "0");
const day = String(now.getDate()).padStart(2, "0");
const hour = String(now.getHours()).padStart(2, "0");
const minute = String(now.getMinutes()).padStart(2, "0");
const second = String(now.getSeconds()).padStart(2, "0");
const milli = String(now.getMilliseconds()).padStart(4, "0");
const m_session_startTime = `${year}-${month}-${day} ${hour}:${minute}:${second}:${milli}`;
console.log(m_session_startTime);
You could use moment.js, it really helps you with formatting dates.
console.log(moment().format('YYYY-MMMM-DD h:mm:ss:SSS'));
<script src="https://momentjs.com/downloads/moment.min.js"></script>
This command does the job pretty well. moment() is a date object, when there are no arguments given like in this example it takes the current time but you can also use moment("2018-12-4") for specific dates.
You can then format the date according to your need,
YYYY is the full year (2018)
MMMM is the full month name (July)
(you can also use MMM for the short version of the month name)
DD is the day as a number (24)
(you can also use dddd for the full name of the day or ddd for the short name)
h is the hour as number (22)
mm is the minute as a number (23)
ss is the second as a number (as an example 22)
SSS is the millisecond as a number (example 245)
Try this?
let date = new Date();
let jsonDate = date.toJSON();
jsonDate = jsonDate.replace(/[TZ]/g, " ");
jsonDate = jsonDate.replace(/\./g, ":");
console.log(jsonDate);
> 2018-07-24 20:32:06:435
Alternatively, if you want to split the entire thing into substrings:
let date = new Date();
let jsonDate = date.toJSON();
jsonDate = jsonDate.replace(/[TZ]/g, " ");
jsonDate = jsonDate.replace(/\./g, ":");
let dateTime = jsonDate.split(" ");
let dt = dateTime[0].split("-");
let tt = dateTime[1].split(":");
let year = dt[0];
let month = dt[1];
let day = dt[2];
let hour = tt[0];
let minute = tt[1];
let second = tt[2];
let mili = tt[3];
console.log(jsonDate);
console.log(dateTime[0]);
console.log(dateTime[1]);
console.log([year, month, day, hour, minute, second, mili].join("~"));
console.log("Date: " + [year, month, day].join("-") + " Time: " + [hour, minute, second, mili].join(":"));
> 2018-07-24 21:03:05:706
> 2018-07-24
> 21:03:05:706
> 2018~07~24~21~03~05~706
> Date: 2018-07-24 Time: 21:03:05:706
As you might have noticed from this response, I work with databases. I have heavy bash, javascript, php, sql, golang background.
Use a moment.js. Great library that is designed to exactly what you would like. You can use the .format option.
var now = moment().format('YYYY-MM-DD HH:mm:ss.SSS');
$('#timeval').text(now);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Current Time: <br>
<a id="timeval"></a>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
https://momentjs.com/
Before I am using angularjs-DatePicker from this npm.
Here,I am able to select the date from the date picker.But now I have to fields as FromDate and ToDate which means the week StartDate and EndDate should show when any date pick in that week.
Ex: Like in Calender 01-08-2017 Start on Tue, So whenever Selects Any date from 01 to 05 then the two fields should show as FromDate as 01 and TODate as 06 and in the same whenever the user selects the 31-07-2017 the the Two fields should show as 30 and 31 of july.
I have an idea to achieve the ToDate from FromDate Calender control onchange event in DotNet as like below mentioned code
Convert.ToDouble(objstart.DayOfWeek)).ToString("dd-MM-yyyy")
But how to achieve this usecase in the angularjs.
Thanks
Ok, so what I'd do is to calculate different dates, and take the min/max depending on the start or end of the week.
Here:
//Use the date received, UTC to prevent timezone making dates shift
var pickedDate = new Date("08-03-2017UTC");
var startSunday = new Date(pickedDate);
startSunday.setDate(pickedDate.getDate() - pickedDate.getDay());
var startMonth = new Date(pickedDate);
startMonth.setDate(1);
var startDate = Math.max(startMonth,startSunday);
console.log("Start:" , new Date(startDate));
var endSaturday = new Date(pickedDate);
endSaturday.setDate(pickedDate.getDate() + (7-pickedDate.getDay()));
var endMonth = new Date(pickedDate);
endMonth.setMonth(pickedDate.getMonth()+1);//Add a month
endMonth.setDate(0);// to select last day of previous month.
var endDate = Math.min(endMonth,endSaturday);
console.log("End" , new Date(endDate));
The trick was to play with the dates, find all the possible start and end dates, then choose the right one with Math.min and Math.max which will compare the dates using their timestamp.
There is very good Library available in JavaScript to handle Date Manipulations.
https://github.com/datejs/Datejs
There is a method
Date.parse('next friday') // Returns the date of the next Friday.
Date.parse('last monday')
Using these method you can get the start and ending date of the week based on the current week.
I hope that it will help.
You can simply achieve this using the library moment. There are a lot of useful functions in this library.
var selectedDate = moment('Mon Aug 10 2017');
//If you want to get the ISO week format(Monday to Sunday)
var weekStart = selectedDate.clone().startOf('isoweek').format('MMM Do');
var weekEnd = selectedDate.clone().endOf('isoweek').format('MMM Do');
//If you want to get the Sunday to Saturday week format
var weekStart = selectedDate.clone().startOf('week').format('MMM Do');
var weekEnd = selectedDate.clone().endOf('week').format('MMM Do');
No need angular directive here, you could use the JavaScript extension which is below.
//get week from date
Date.prototype.getWeekNumber = function (weekstart) {
var target = new Date(this.valueOf());
// Set default for weekstart and clamp to useful range
if (weekstart === undefined) weekstart = 1;
weekstart %= 7;
// Replaced offset of (6) with (7 - weekstart)
var dayNr = (this.getDay() + 7 - weekstart) % 7;
target.setDate(target.getDate() - dayNr + 0);//0 means friday
var firstDay = target.valueOf();
target.setMonth(0, 1);
if (target.getDay() !== 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
return 1 + Math.ceil((firstDay - target) / 604800000);;
};
//get date rance of week
Date.prototype.getDateRangeOfWeek = function (weekNo, weekstart) {
var d1 = this;
var firstDayOfWeek = eval(d1.getDay() - weekstart);
d1.setDate(d1.getDate() - firstDayOfWeek);
var weekNoToday = d1.getWeekNumber(weekstart);
var weeksInTheFuture = eval(weekNo - weekNoToday);
var date1 = angular.copy(d1);
date1.setDate(date1.getDate() + eval(7 * weeksInTheFuture));
if (d1.getFullYear() === date1.getFullYear()) {
d1.setDate(d1.getDate() + eval(7 * weeksInTheFuture));
}
var rangeIsFrom = eval(d1.getMonth() + 1) + "/" + d1.getDate() + "/" + d1.getFullYear();
d1.setDate(d1.getDate() + 6);
var rangeIsTo = eval(d1.getMonth() + 1) + "/" + d1.getDate() + "/" + d1.getFullYear();
return { startDate: rangeIsFrom, endDate: rangeIsTo }
};
Your code can be look like this
var startdate = '01-08-2017'
var weekList = [];
var year = startdate.getFullYear();
var onejan = new Date(year, 0, 1);//first january is the first week of the year
var weekstart = onejan.getDay();
weekNumber = startdate.getWeekNumber(weekstart);
//generate week number
var wkNumber = weekNumber;
var weekDateRange = onejan.getDateRangeOfWeek(wkNumber, weekstart);
var wk = {
value: wkNumber
, text: 'Week' + wkNumber.toString()
, weekStartDate: new Date(weekDateRange.startDate)
, weekEndDate: new Date(weekDateRange.endDate)
};
weekList.push(wk);
I guess there is no directive or filter for this, you need to create one for yourself. you can refer date object from date-time-object
Good afternoon in my timezone.
I want to compare two dates , one of them is inserted by the user and the other is the present day. Snippet of code :
var dateString = "2012-01-03"
var date = new Date(dateString);
date < new Date() ? true : false;
This returns true, i think under the hood both Date objects are transformed to milliseconds and then compared , and if it is this way the "Today" object is bigger because of the hours and minutes.So what i want to do is compare dates just by the day month and year.What is the best approach ? Create a new Date object and then reset the hours minutes and milliseconds to zero before the comparison? Or extract the day the month and year from both dates object and make the comparison ? Is there any better approach ?
Thanks in advance
With the best regards.
Happy new year
Set the time portion of your created date to zeros.
var d = new Date();
d.setHours(0,0,0,0);
Since it's in yyyy-mm-dd format, you can just build the current yyyy-mm-dd from date object and do a regular string comparison:
var currentDate = new Date();
var year = currentDate.getFullYear();
var month = currentDate.getMonth()+1;
if (month < 10) month = "0" + month;
var day = currentDate.getDate();
if (day < 10) day = "0" + day;
currentDate = year + "-" + month + "-" + day;
var dateString = "2012-01-03"
var compareDates = dateString < currentDate ? true : false;
document.write(compareDates);
A production-ready example based on top of Accepted Answer
Add the following function to your Javascript
Date.prototype.removeTimeFromDate = function () {
var newDate = new Date(this);
newDate.setHours(0, 0, 0, 0);
return newDate;
}
Invoke it whenever you wish to compare
firstDate.removeTimeFromDate() < secondDate.removeTimeFromDate()
I have this code:
var fd=1+self.theDate.getMonth() +'/'+ today+'/'+self.theDate.getFullYear();
It works, but it's format is Month, Day, Year.
I need to change it to: Day, Month Year.
So, I tried this:
var fd=1+today +'/'+ self.theDate.getMonth()+'/'+self.theDate.getFullYear();
Now, my change does not work. Is it that I have not done it properly or is my change right?
Thanks
I expect the correct answer is this:
var fd=today +'/'+ (self.theDate.getMonth() + 1) +'/'+self.theDate.getFullYear();
This leaves today alone, and groups Month so that it does a proper number addition instead of string concatenation.
var theDate = new Date();
var today = theDate.getDate();
var month = theDate.getMonth()+1; // js months are 0 based
var year = theDate.getFullYear();
var fd=today +'/'+ month +'/'+year
or perhaps you prefer 22/05/2011
var theDate = new Date();
var today = theDate.getDate();
if (today<10) today="0"+today;
var month = theDate.getMonth()+1; // js months are 0 based
if (month < 10) month = "0"+month;
var year = theDate.getFullYear();
var fd=""+today +"/"+ month +"/"+year
You are no longer adding 1 to the month, you are adding it to today. Make sure to parenthesize this since "x" + 1 + 2 => "x12" but "x" + (1 + 2) => "x3"