I am trying to get specific date in java script.
What I am trying to do is.
I have variable called frequency Which can be Daily , Weekly and Monthly
if(frequency=="daily")
{
date='current_date -2 days';
}
else if ( frequency== 'weekly')
{
date='current_date -8 days';
}
else if ( frequency == 'monthly')
{
date='current_date -32 days';
}
This is the way I get current date with required format.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
var hh = today.getHours();
var min = today.getMinutes();
var ss = today.getSeconds();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
// today = mm+'/'+dd+'/'+yyyy;
today = yyyy + "-" + mm + "-" + dd + " " + hh + ":" + mm + ":" + ss ;
alert("Today's date :"+today);
But, I am facing problem in subtracting the days
can anyone give an idea how can I achieve this.
You can simply do this:
function setDate(frequency) {
var today = new Date(),
date;
if (frequency == "daily") {
date = today.getTime() - (2*24*60*60*1000); // 2 days 24 hrs 60 mins 60 secs 1000 ms
} else if (frequency == 'weekly') {
date = today.getTime() - (8*24*60*60*1000);
} else if (frequency == 'monthly') {
date = today.getTime() - (32*24*60*60*1000);
}
return new Date(date);
}
document.querySelector('pre').innerHTML = setDate('monthly');
<pre></pre>
You need to convert days into time in ms miliseconds to convert it in time then you can subtract it from current time in ms after it you can return it as a new Date(date);.
You can use http://momentjs.com/ which makes date manipulation a breathe.
Related
I have been trying to subtract date format (yyyy-MM-dd) to another date format but to no avail. I looked up online but it's confusing and I got this error which says that is it not a function for today.getDate(). Could anyone provide me with a solution in subtracting? I am at my wits end.
Thanks in advance.
for (var i = 0; i < 3; i++) {
var startDate = "2020-08-19"
var today = new Date();
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 = yyyy + '-' + mm + '-' + dd;
today.setDate(today.getDate() - startDate);
console.log(today.getDate() - startDate);
if ((startDate - today) >= 30) {
console.log("hello");
} else if ((startDate - today) <= 30) {
console.log("bye");
}
};
You are mixing a few concepts:
var today = new Date();
This creates a Date object that wraps the number of milliseconds from 1/1/1970 at midnight UTC.
today = yyyy + '-' + mm + '-' + dd;
This is creating a string.
If your goal is to find out how many days are between two dates, your best bet is to use milliseconds since Unix epoch, sometimes called "Unix timestamps." With these timestamps, subtracting is straightforward since they're just numbers; you'll get the number of milliseconds between the two points of time. Getting from timestamps to number of days then becomes a matter of division:
const diff = Date.now() - Date.parse("2020-08-19");
const numDays = diff / (1000 * 60 * 60 * 24);
This question already has answers here:
Adding months to a Date in JavaScript [duplicate]
(2 answers)
Closed 4 years ago.
I have this code which works fine. It gives me todays date in a specific format.
function fetchTime() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = yyyy + '-' + mm + '-' + dd;
return (today);
}
I'm also trying to get today's date minus 1 month. I thought this would be simple, I just removed the +1. So I have this code:
function fetchTime() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth();
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = yyyy + '-' + mm + '-' + dd;
return (today);
}
This gives me the output 2019-00-17 which should be 2018-12-17
Can anyone tell me the right way to do this? My question is specific to getting the date out in the required format, whereas most examples I have seen do not output the right format as part of the date change.
I would separate the formatting from the fetching. You could make your existing formatting function take an optional parameter that defaults to today, so you could call it like you already were for today's date.
function formatTime(date) {
var dateToFormat = date || new Date();
var dd = dateToFormat.getDate();
var mm = dateToFormat.getMonth() + 1;
var yyyy = dateToFormat.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
return (yyyy + '-' + mm + '-' + dd);
}
Then you could also call it with today's date minus a month or any other date
formatTime(); //will default to today
var today = new Date();
formatTime(addMonths(today,-1)); //format last month's date
As pointed out by RobG in the comments you would need to implement an addMonths function as in Adding months to a Date in JavaScript
function addMonths(date, months) {
var d = date.getDate();
date.setMonth(date.getMonth() + +months);
if (date.getDate() != d) {
date.setDate(0);
}
return date;
}
For substracting in moment.js:
moment().subtract(1, 'months').format("DD-MM-YYYY")
Documentation:
http://momentjs.com/docs/#/manipulating/subtract/
You should subtract months by getting the current month, then subtracting the number of months you want and then updating the date variable like this.
function fetchTime() {
var today = new Date();
today.setMonth(today.getMonth() - 1);
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = yyyy + '-' + mm + '-' + dd;
return (today);
}
Because your desired format is an ISO 8601 date, you could use JavaScript's .toISOString. You are only concerned with the first 10 characters though (not time), so you'd want to add .substring(0,10).
Date.prototype.toISODateString = function() { return this.toISOString().substring(0,10); }
Date.prototype.addMonths = function(val) { this.setMonth(this.getMonth()+val); return this;}
var date = new Date();
var todayFormatted = date.toISODateString();
console.log(todayFormatted);
var lastMonthFormatted = date.addMonths(-1).toISODateString();
console.log(lastMonthFormatted);
I've made the formatting steps a function called toISODateString() and added it to the Date prototype, which is a fancy way of saying "You can chain .toISODateString() to any Date now".
To set the date back a month, I've used .setMonth(). I also turned this into a function called addMonths.
Use the same code, but remove a month. Example:
function fetchTime() {
var today = new Date();
today.setMonth(today.getMonth() - 1);
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = yyyy + '-' + mm + '-' + dd;
return (today);
}
I want to check if date is today, then user should not be able to pick expired time. However, if the date selected is tomorrow, then any time can be selected.
I am trying to do a check in jquery, but not sure how to check. Below is the code used:
var targetTime = new Date().setMinutes(-5).valueOf();
var today = new Date();
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);
if (jQuery('#startDatepicker').find("input").val() == today) {
alert("Yes");
var currentTime = jQuery('#startTimepicker').find("input").val();
alert(currentTime);
alert(targetTime);
if (currentTime <= targetTime) {
//Time Expired
alert("HI");
}
}
The date is in the format of "MM/DD/YYYY", and the time is in format of "hh:mm a". Expired time of 5 minutes is allowed. How to validate the expired time using jQuery?
Thanks
Use same Date object you have:
// .valueOf() gives time in milliseconds
var currentTime = new Date('25/12/2016 01:52').valueOf();
var targetTime = new Date().setMinutes(-5).valueOf();
if (currentTime <= targetTime) {
// expired
} else {
// not expired
}
I am working on JavaScript validation where I am validating whether a textbox date is equal to the current date or not.
If its greater or equal to today's date than do something, if its less than today's date then show error message.
Note: In my textbox I have converted date into dd/MM/yyyy format. So I need to check textbox date with current date in dd/MM/yyy format only. Here is my code:
function ValidateDate() {
var EffectiveDate = $.trim($("[id$='txtFromDate']").val());
var Today = new Date();
if(EffectiveDate<Today())
{
//Show Error Message
}
else
{
//Do something else
}
I need the date to be in dd/MM/yyyy format for checking my textbox date, so my Today value has to be in dd/MM/yyyy format only.
function ValidateAddNewCourseCharge() {
var EffectiveDate = $.trim($("[id$='txtFromDate']").val());
var Today = new Date();
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
}
var Today = dd + '/' + mm + '/' + yyyy;
dateFirst = EffectiveDate.split('/');
dateSecond = Today.split('/');
var value = new Date(dateFirst[2], dateFirst[1], dateFirst[0]);
var current = new Date(dateSecond[2], dateSecond[1], dateSecond[0]);
if (EffectiveDate == "") {
showErrorMessagePopUp("Please Select a Date for Course Charge!");
return false;
}
else {
if (value < current) {
showErrorMessagePopUp("Date should not be less than Present Date!");
return false;
}
}
return true;
}
First, we have to find the current date -- below is code that finds it. Then, compare the result with the value entered in TextBox.
var today = new Date();
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;
document.write(today);
var EffectiveDate = $.trim($("[id$='txtFromDate']").val());
I think it will help for you
var getdate = new Date($("[id$='txtFromDate']").val());
var curDate = new Date();
alert(getdate - curDate === 0);
alert(getdate - curDate < 0);
alert(getdate - curDate > 0);
I want to find date by subtracting X number of days from a particular date in JavaScript. My JavaScript function accepts 2 parameters. One is the date value and the other is the number of days that needs to be subtracted.
For example, I pass my argument date as 27 July 2009 and i pass my other argument as 3. So i want to calculate the date 3 days before 27 July 2009. So the resultant date that we should get is 24 July 2009. How is this possible in JavaScript. Thanks for any help.
Simply:
yourDate.setDate(yourDate.getDate() - daysToSubtract);
function date_by_subtracting_days(date, days) {
return new Date(
date.getFullYear(),
date.getMonth(),
date.getDate() - days,
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds()
);
}
Never go for this solution
yourDate.setDate(yourDate.getDate() - daysToSubtract);
it wont work in case your date is 1st of any month and you want to delete some days say 1.
Instead go for below solution which will work always
var newDate = new Date( yourDate.getTime() - (days * 24 * 60 * 60 * 1000) );
Here i am posting one more answer and that will return date in specific format.
First you can get current date 10/08/2013 as below
function Cureent_Date() {
var today_GMT = new Date();
var dd = today_GMT.getDate();
var mm = today_GMT.getMonth() + 1; //January is 0!
var yyyy = today_GMT.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
current_date = mm + '/' + dd + '/' + yyyy;
alert("current_date"+current_date);
Back_date();
}
Now Get back date base on X days
function Back_date()
{
var back_GTM = new Date(); back_GTM.setDate(back_GTM.getDate() - 2); // 2 is your X
var b_dd = back_GTM.getDate();
var b_mm = back_GTM.getMonth()+1;
var b_yyyy = back_GTM.getFullYear();
if (b_dd < 10) {
b_dd = '0' + b_dd
}
if (b_mm < 10) {
b_mm = '0' +b_mm
}
var back_date= b_mm + '/' + b_dd + '/' + b_yyyy;
alert("back_date"+back_date);
}
So, Today is 10/08/2013 so it will return 10/06/2013.
Check Live Demo here
Hope this answer will help you.
Here's an example, however this does no kind of checking (for example if you use it on 2009/7/1 it'll use a negative day or throw an error.
function subDate(o, days) {
// keep in mind, months in javascript are 0-11
return new Date(o.getFullYear(), o.getMonth(), o.getDate() - days);;
}
This is what I would do. Note you can simplify the expression, I've just written it out to make it clear you are multiplying the number of days by the number of milliseconds in a day.
var newDate = new Date( yourDate.getTime() - (days * 24 * 60 * 60 * 1000) );
Just another option, which I wrote:
DP_DateExtensions Library
It's probably overkill if ALL you want to do is one calculation, but if you're going to do more date manipulation you might find it useful.
Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc.
this is in reference to above answer
check this fiddle
https://jsfiddle.net/uniyalguru/azh65aa0/
function Cureent_Date() {
var today_GMT = new Date();
var dd = today_GMT.getDate();
var mm = today_GMT.getMonth() + 1; //January is 0!
var yyyy = today_GMT.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
current_date = mm + '/' + dd + '/' + yyyy;
I have created a function for date manipulation. you can add or subtract any number of days, hours, minutes.
function dateManipulation(date, days, hrs, mins, operator) {
date = new Date(date);
if (operator == "-") {
var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
var newDate = new Date(date.getTime() - durationInMs);
} else {
var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
var newDate = new Date(date.getTime() + durationInMs);
}
return newDate;
}
Now, call this function by passing parameters. For example, here is a function call for getting date before 3 days from today.
var today = new Date();
var newDate = dateManipulation(today, 3, 0, 0, "-");