Javascript get date 30 days ago [duplicate] - javascript

This question already has answers here:
How to subtract days from a plain Date?
(36 answers)
Closed 5 years ago.
I am trying to populate two date input fields, one with today's date and one with the date 30 days ago(last month).
I am getting an error in my console: priordate.getDate is not a function
Here is my code, not sure what I am doing wrong:
//today's date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0, so always add + 1
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd};
if(mm<10){mm='0'+mm};
today = yyyy+'-'+mm+'-'+dd;
//30 days ago
var beforedate = new Date();
var priordate = new Date().setDate(beforedate.getDate()-30);
var dd2 = priordate.getDate();
var mm2 = priordate.getMonth()+1;//January is 0, so always add + 1
var yyyy2 = priordate.getFullYear();
if(dd2<10){dd2='0'+dd2};
if(mm2<10){mm2='0'+mm2};
var datefrommonthago = yyyy2+'-'+mm2+'-'+dd2;
// Set inputs with the date variables:
$("#fromdate").val(datefrommonthago);
$("#todate").val(today);

You'll instead want to use:
var priordate = new Date(new Date().setDate(beforedate.getDate()-30));
if you want it on one line. By using:
new Date().setDate(beforedate.getDate()-30);
you're returning the time since epoch (a number, not a date) and assigning it to priordate, but it's not a Date anymore and so does not have the getDate function.

This is because setDate() returns a number, not a Date Object.
In any I case I'd strongly recommend using momentjs or date-fns as the internal Date object in JavaScript is broken in all kind of ways. See this talk: https://www.youtube.com/watch?v=aVuor-VAWTI

Change this:
var priordate = new Date().setDate(beforedate.getDate()-30);
to this:
var priordate = new Date();
priordate.setDate(beforedate.getDate()-30);

Related

getMonth() in Javascript from format dd/mm/yyyy [duplicate]

This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Closed 3 years ago.
I have a date in format dd/mm/yyyy and when I try to use getMonth() I get the dd field.
For example if I have "01/12/2019" it will take 01 as month instead of 12. Is there a way to get the month from this format?
This is my code:
var beginDate = document.getElementById("beginDate").value;
var month = new Date(beginDate).getMonth();
inside beginDate there's "01/10/2019" (October 1st 2019)
It's better to use any external libraries like momentjs or datejs. Try this it may solve your problem now.
const date = "01/12/2019";
const split = date.split('/');
console.log('day', split[0])
console.log('month', split[1])
console.log('year', split[2])
var date = moment('01/12/2019', 'DD/MM/YYYY');
console.log(date.month()+1);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
You can use something like Moment.js
const beginDate = "22/05/2019"
const date = moment(beginDate, 'DD/MM/YYYY');
const month = date.format('M');
console.log(month)
//05
Make it easy.
You don't need external libraries:
var beginDate = "01/10/2019";
var timeZone = 'your time zone'; //en-GB etc...
var month = new Date(beginDate).toLocaleString(timeZone , {month: "2-digit"}); //month = 10
I don't think that you need some external library to do this task. You should use javascript date object to get it done easily, getMonth() returns month indexed from 0 to 11. Prefer javascript always instead of unnecessarily importing external js files for libraries
var beginDate = document.getElementById("beginDate").value;
let reg = /(\d\d)\/(\d\d)\/(\d+)/gi;
const[date,mon,year] = reg.exec(beginDate).splice(1);
month = new Date(year,mon-1,date).getMonth(); // months are indexed from 0 to 11 for jan to dec
console.log(month); // 0 for jan and 11 for dec
Month in javascript is 0 indexed that mean 0 represent January, So you need to add 1 to get the month correctly
function getMonth(dt) {
let splitDt = dt.split('/');
return new Date(`${splitDt[2]}-${splitDt[1]}-${splitDt[0]}`).getMonth() + 1;
}
console.log(getMonth("01/10/2019"))
1st oct
You can get months using getMonth() as shown below, But here 0=January, 1=February etc.
var date = "05/12/2019"
var d = new Date(date);
var n = d.getMonth();
console.log(n)

How do I get the time in milliseconds from 2 different string?

I have the following code which I get from parameters in the URL.
This is what I have in the URL
&dateStart=15.01.2015&timeStart=08%3A00&
After getting the parameters I have the following: 15.01.2015:08:00
Using Javascript how can I parse this string to get the date in milliseconds?
Date.parse(15.01.2015:08:00)
But obviously this doesn't work.
Date.parse(15-01-2015)
This works and I can change this but then how do I add or get the milliseconds from the time??
This is quite possibly the ugliest JavaScript function I've written in my life but it should work for you.
function millisecondsFromMyDateTime(dateTime) {
var dayMonth = dateTime.split('.');
var yearHourMinute = dayMonth[2].split(':');
var year = yearHourMinute[0];
var month = parseInt(dayMonth[1]) - 1;
var day = dayMonth[0];
var hour = yearHourMinute[1];
var minute = yearHourMinute[2];
var dateTimeObj = new Date(year, month, day, hour, minute, 0, 0);
return dateTimeObj.getTime();
}
It will work with the format that your DateTime is in aka day.month.year:hours:minutes.
You can achieve it using Javascript Date Object and JavaScript getTime() Method:
var dateString="01.15.2015 08:00";
var d = new Date(dateString);
console.log(d);
var ms=d.getTime();
console.log(ms);
ms+=10000;
console.log(new Date(ms));
Here is a DEMO Fiddle.
Note: Change your date string from 15.01.2015:08:00 to "01.15.2015 08:00" because it's not a valid Date format.
Check for format
Date() in javascript :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Format allowed :
https://www.rfc-editor.org/rfc/rfc2822#page-14
You can try to use moment.js library like this:
moment('15.01.2015 08:00', 'DD.MM.YYYY HH:mm').milliseconds()
Just for the sake of completion, you can always extract the information and create a Date object from the extracted data.
var dateStart = '15.01.2015'
var timeStart = '08:00';
var year = dateStart.substring(6,10);
var month = dateStart.substring(3,5);
var day = dateStart.substring(0,2);
var hour = timeStart.substring(0,2);
var mins = timeStart.substring(3,5);
var fulldate = new Date(year, month-1, day, hour, mins);
console.log(fulldate.getTime());

Get future date using Javascript

I am trying to get the date which is 14th of January,2014 in Javascript but it is returning invalid date.
var clock;
$(document).ready(function () {
var currentDate = new Date();
var futureDate = new Date(currentDate.setFullYear(2014,17,1) + 1, 0, 1);
alert(futureDate);
});
Jsfiddle:http://jsfiddle.net/zJF35/
Try var futureDate = new Date(new Date().getFullYear(), 0, 14);
setFullYear() method sets the full year for a specified date according to local time.
dateObj.setFullYear(yearValue[, monthValue[, dayValue]])
here the middle one parameter is month value in which you are passing 17 which is not making sense and its converting into next year.
So You probably want this
var futureDate = new Date(currentDate.setFullYear(2014,0,14));
Js Fiddle Demo
You can try
var futureDate = new Date(2014,0,14);
Any future date in JavaScript (postman test uses JavaScript) can be retrieved as:
var dateNow = new Date();
var twoWeeksFutureDate = new Date(dateNow.setDate(dateNow.getDate() + 14)).toISOString();
//Note it returns 2 weeks future date from now.

How to subtract two dates in javascript?

I want to get the difference between tow dates in javascript but my problem is that the first date is the currenet date of the PC :
today = new Date();
and the other date is a text format date like this for example:
other_date = '15.11.2013';
I want the today date to be same format as other_date and then subtract them , How can I change the format of the today to make the same as other_date ? and How I can make them both as date format to subtract them and get the difference correctly???
I would simply use the split function to get the date parts of the date string:
var today = new Date();
var other_date = '15.11.2013';
var dateparts = other_date.split('.');
var otherDate = new Date(dateparts[2], dateparts[1]-1, dateparts[0]); // substract 1 month because month starting with 0
var difference = today.getTime() - otherDate.getTime(); // difference in ms

Javascript get date in format [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 3 years ago.
I want to get today's date in the format of mm-dd-yyyy
I am using var currentDate = new Date();
document.write(currentDate);
I can't figure out how to format it.
I saw the examples var currentTime = new Date(YY, mm, dd); and currentTime.format("mm/dd/YY");
Both of which don't work
I finally got a properly formatted date using
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 = mm+'/'+dd+'/'+yyyy;
document.write(today);'`
This seems very complex for such a simple task.
Is there a better way to get today's date in dd/mm/yyyy?
Unfortunately there is no better way, but instead of reinventing the wheel, you could use a library to deal with parsing and formatting dates: Datejs
<plug class="shameless">
Or, if you find format specifiers ugly and hard to decipher, here's a concise formatting implementation that allows you to use human-readable format specifiers (namely, the Date instance getters themselves):
date.format("{Month:2}-{Date:2}-{FullYear}"); // mm-dd-yyyy
</plug>
var today = new Date();
var strDate = 'Y-m-d'
.replace('Y', today.getFullYear())
.replace('m', today.getMonth()+1)
.replace('d', today.getDate());
Simple answer is no. Thats the only way to do it that I know of.
You can probably wrap into a function that you can reuse many times.
date.js is what you need. For example, snippet below is to convert a date to string as Java style
new Date().toString('M/d/yyyy')
function dateNow(splinter){
var set = new Date();
var getDate = set.getDate().toString();
if (getDate.length == 1){ //example if 1 change to 01
getDate = "0"+getDate;
}
var getMonth = (set.getMonth()+1).toString();
if (getMonth.length == 1){
getMonth = "0"+getMonth;
}
var getYear = set.getFullYear().toString();
var dateNow = getMonth +splinter+ getDate +splinter+ getYear; //today
return dateNow;
}
format this function is mm dd yyyy
and the dividing you can choice and replace if you want... for example
dateNow("/") you will get 12/12/2014
There is nothing built in, but consider using this if you are already using jQuery (and if not, then you should consider that as well!)
http://plugins.jquery.com/project/jquery-dateFormat
(new Date()).format("MM-dd-yyyy")
N.B. month is "MM" not "mm"
function appendZeros(value,digits){
var c= 1;
initValue = value;
for(i=0;i<digits-1;i++){
c = c*10;
if( initValue < c ){
value = '0' + value;
}
}
return value;
}

Categories