set javascript date object to before 30 days - javascript

Lets say now the date is 10/07/2015, ie If I create a javascript date object like as shown below I will get todays date as 07/10/2015
var now = new Date();
So if the date is 10/07/2015 I want 30 days back date i.e 07/09/2015.
I did like as shown below but for that I got 31/08/2015
var now = new Date();
now .setDate(-30);
Can anyone please tell me some solution for this

You can try like this:
Date.today().add(-30).days();
And if you want then moment.js is really good when dealing with dates
moment().subtract(30, 'days');
And if you dont want to use any library then
var now = new Date()
var prev = new Date().setDate(now.getDate()-30)

You could have simply use now.getDate():
var now = new Date();
document.write(now);
now.setDate(now.getDate() - 30);
document.write("<br/>");
document.write(now);

A Date object internally contains a value that corresponds to the number of milliseconds passed since 1 January, 1970 UTC.
As such, using this value (accessible via Date.prototype.valueOf()) you can add or subtract any size of "simply calculated" time interval. By simply calculated I mean anything that can be calculated using simple arithmetics, such as (for example..) "1 day 4 hours and 2 minutes" is equal to (((1 * 24) + 4) * 60 + 2) * 60 * 1000. You can add / subtract that to any starting time and create a new Date object:
var startDate = new Date();
var newDate = new Date(startDate.valueOf() + ((((1 * 24) + 4) * 60 + 2) * 60 * 1000));
alert(newDate);
In the specific case of days offset, simply use this formula:
days * 24 * 60 * 60 * 1000

Related

how to create JavaScript code for date object today + 11 days in JavaScript Shopify

I want to inject date into html in shopify description product
That it would say
We will ship the product from today + 11 days.....
And if it falls to saturday or sunday, it will be moved to monday cause we are closed on saturday or sunday
code is this for now, but dunno how to move it to first monday if necessary
// get the destination within the DOM
var wrapper = document.getElementById('productEta'),
// get today as a js Date object
today = new Date(),
// get the Unix of today (miliseconds) and add desired time (3 weeks)
etaUnix = today.getTime() + (60 * 60 * 24 * 11 * 1000),
// convert the new time to date object and then to a human readable string
etaForHumans = new Date(etaUnix).toDateString();
// set the destination inner html to be what it already is
// plus a space and the human readable string.
wrapper.innerHTML += ' ' + etaForHumans;
<div id="productEta">Product will arrive by: </div>
But something is wrong with the script also
This actually ain't too hard.
The Date object provides a function getDay() which returns the day of the week.
It's an integer between 0 and 6.
You can do it like this:
var days = 4;
etaUnix = new Date(today.getTime() + (60 * 60 * 24 * days * 1000));
console.log(etaUnix.getDay())
switch (etaUnix.getDay()) {
case 0:
//sunday
days++;
break;
case 6:
//saturday
days += 2;
break;
}
etaUnix = new Date(today.getTime() + (60 * 60 * 24 * days * 1000));
// convert the new time to date object and then to a human readable string
etaForHumans = new Date(etaUnix).toDateString();
In the switch block where handling saturdays and sundays and simply adding one or two days to the date.
By the way - there are some typos in your code. There needs to be a ; at the end of a statement not a ,
// get the destination within the DOM
var wrapper = document.getElementById('productEta'),
// get today as a js Date object
today = new Date(),
// get the Unix of today (miliseconds) and add desired time (3 weeks)
etaUnix = today.getTime() + (60 * 60 * 24 * 11 * 1000),
// convert the new time to date object and then to a human readable string
etaForHumans = new Date(etaUnix);
var day = etaForHumans.getDay()
if(day==0)
etaForHumans.setDate(etaForHumans.getDate() + 1);
if(day==6)
etaForHumans.setDate(etaForHumans.getDate() + 2);
// set the destination inner html to be what it already is
// plus a space and the human readable string.
wrapper.innerHTML += ' ' + etaForHumans+ ' ' + day;
<div id="productEta">Product will arrive by: </div>
var wrapper = document.getElementById('productEta');
var today = new Date(Date.parse('2019-03-05'));
var etaDate = new Date(today.getTime() + (60 * 60 * 24 * 11 * 1000))
while(etaDate.getDay() == 0 || etaDate.getDay() == 6){
//Add one day until it is not saturday or sunday
etaDate.setTime(etaDate.getTime() + (60 * 60 * 24 * 1000));
}
var etaForHumans = etaDate.toDateString();
// set the destination inner html to be what it already is
// plus a space and the human readable string.
wrapper.innerHTML += ' ' + etaForHumans;
<div id="productEta">Product will arrive by: </div>
momentJS. Check it out. Allows you play with dates in a sane way. Has plugins for things like asking for the nextBusinessDay() and much more.
Don't fiddle with dates and vanilla Javascript unless you are an ace Javascript coder. It sucks and momentJS exists for good reason. Less suckage.

Javascript countdown and Timezones

enter image description here
basically I insert a row with a datetime + interval (something in the future) with a SQL query.
$interval = new DateInterval('PT'.$H.'H'.$i.'M'.$s.'S');
$date = new DateTime(); $date->add($interval);
$query = $conn->prepare("INSERT INTO profiles_in_missions (id_pim, id_profile, id_mission, time) VALUES (NULL, :idprofile, :idmission,:time)");
$query->bindValue(':idprofile', $tableau[0]);
$query->bindValue(':idmission', $id);
$query->bindValue(':time', $date->format('Y-m-d H:i:s'));
$query->execute();
If my pc shows: 23:40, and if i insert DateTime with interval of +8minutes, this query will store 21:48 in the database. Till now okay, my database is GTM+00 and my pc default browser is GTM+2.
Once stored, i am trying to pick this date who got (in that case) -2h+8m and and make a countdown.
Now the problem: To make the countdown, i am using javascript and i do 21:48-now(); BUT he will always end 2h faster than normal, because the stored date (21:48) in MYSQL with GTM+00 BUT Javascript now(); is getting my default browser time GTM+2.
Is there a way to make Javascript work with server Timezone GTM+00? How can i fix my problem? There is all my code for the countdown:
<script>
var t = document.getElementById('myInputTimer').value;
var countDownDate = new Date(t).getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
new Date().getTime() (which can be replaced with Date.now()) simply returns the number of milliseconds from date zero. Timezone isn't a factor here, where timezone becomes a factor is here:
var t = document.getElementById('myInputTimer').value;
var countDownDate = new Date(t).getTime();
If the string you use to create the date object doesn't contain any timezone information, it assumes the timezone of the browser.
I'm assuming this string is the date you have in UTC time?
One solution is to make sure this string contains timezone information, which means it would look like this: 2017-06-03T22:23:00+00:00
Another solution is to correct for the timezone offset after you've parsed the date. So if new Date("2017-06-03 22:23:00") gives you Sat Jun 03 2017 22:23:00 GMT+0200 (CEST) which is 20:23 you can correct it by subtracting the timezone offset:
var countDownDate = new Date(t).getTime() - (new Date().getTimezoneOffset() * 60 * 1000);
.getTimezoneOffset() returns the timezone offset in minutes, we calculate how many milliseconds it is and then subtract it from the milliseconds returned by .getTime()
Using a string to create a date isn't the best idea however since it's implementation dependent and unreliable. It's better to parse out the various components (year, month, day, hours, and so on) and construct the date with those. You can use a regexp to parse out the components like this:
var dateParts = t.match(/\d+/g);
And the best part is that now you can use Date.UTC() instead of new Date(t).getTime() to get the time in UTC directly:
var countDownDate = Date.UTC.apply(null, dateParts);

Number of weeks between two dates using JavaScript

I'm trying to return the number of weeks between two dates using JavaScript.
So I have the following variables:
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if(day < 10) { day= '0' + day; }
if(month < 10) { month = '0' + month; }
var dateToday = day + '/' + month + '/' + year;
var dateEndPlacement = '22/06/2014';
I've also prefixed the days and months with 0 if they are less than 10. Not sure if this is the correct way to do this... so alternative ideas would be welcomed.
And then I pass these two dates to the following function:
function calculateWeeksBetween(date1, date2) {
// The number of milliseconds in one week
var ONE_WEEK = 1000 * 60 * 60 * 24 * 7;
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms);
// Convert back to weeks and return hole weeks
return Math.floor(difference_ms / ONE_WEEK);
}
However I get the error:
Uncaught TypeError: Object 04/04/2014 has no method 'getTime'
Any ideas what I am doing wrong?
For those that are asking/gonna ask, I'm calling the function like this:
calculateWeeksBetween(dateToday, dateEndPlacement);
I would recommend using moment.js for this kind of thing.
But if you want to do it in pure javascript here is how I would do it:
function weeksBetween(d1, d2) {
return Math.round((d2 - d1) / (7 * 24 * 60 * 60 * 1000));
}
Then call with
weeksBetween(new Date(), new Date(2014, 6, 22));
You are storing your dates as strings ('22/06/2014'). getTime is a method of Date. You need to create Date objects for the dates, and pass those into the function.
var dateToday = new Date(year, month - 1, day);
var dateEndPlacement = new Date(2014, 5, 22);
calculateWeeksBetween(dateToday, dateEndPlacement);
As #Mosho notes, you can also subtract the dates directly, without using getTime.
If you need actual weeks between to dates, and not the number of seven days between them:
const week = 7 * 24 * 60 * 60 * 1000;
const day = 24 * 60 * 60 * 1000;
function startOfWeek(dt) {
const weekday = dt.getDay();
return new Date(dt.getTime() - Math.abs(0 - weekday) * day);
}
function weeksBetween(d1, d2) {
return Math.ceil((startOfWeek(d2) - startOfWeek(d1)) / week);
}
You can use moment itself have all the functionality I mentioned the below code which could work perfectly
var a = moment(a, 'DD-MM-YYYY');
var b = moment(b, 'DD-MM-YYYY');
days=b.diff(a, 'week');
don't forget to use moment js CDN
subtract dates (which, unformatted, are the number of seconds elapsed since 1 January 1970 00:00:00) , divide by 604,800,000 (milliseconds per week).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
You should convert dateToday and dateEndPlacement to Date type.
Please read Converting string to date in js

Subtracting days from a date in javascript

I have 2 <input type="text"> tags and I enter dates in them like this 22-05-2013
I want to subtract 22-06-2012 from that date
How do I do this?
I've tried this code but it didn't work:
function returnDate(nDays){
var now = new Date();
var dayOfTheWeek = now.getDay();
now.setTime(now.getTime() - nDays * 24 * 60 * 60 * 1000);
alert(now); // returns current date
alert(now.getFullYear() + "/"+(now.getMonth()+1)+"/"+now.getDate()) // returns new calculated date
}
So I need the difference between 22-05-2013 and 22-06-2012
The best way to do it would be to use Moment.js. It has fantastic support for dates.
In javascript you could subtract 2 Date objects and this will return the number of milliseconds between them. For example:
var date1 = new Date('2013-06-22 01:00:00');
var date2 = new Date('2013-06-22 01:00:01');
var result = date2 - date1;
alert(result); // shows 1000 which is 1 second
Simple:
new Date(mydate1 - mydate2).getDay() ;
This will give you the number of days.
I would suggest you use Date.js though, which would be even simpler.

How can I count the days between two dates in javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to calculate the number of days between two dates using javascript
I have those dates :
27/09/2011
29/10/2011
and I'd like to return the days between those dates (in the example, should be 33 days).
How can I do it on javascript (or jquery?)?
var daysBetween = (Date.parse(DATE1) - Date.parse(DATE2)) / (24 * 3600 * 1000);
function days_between(date1, date2) {
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)
// Convert back to days and return
return Math.round(difference_ms/ONE_DAY)
}
http://www.mcfedries.com/JavaScript/DaysBetween.asp
// split the date into days, months, years array
var x = "27/09/2011".split('/')
var y = "29/10/2011".split('/')
// create date objects using year, month, day
var a = new Date(x[2],x[1],x[0])
var b = new Date(y[2],y[1],y[0])
// calculate difference between dayes
var c = ( b - a )
// convert from milliseconds to days
// multiply milliseconds * seconds * minutes * hours
var d = c / (1000 * 60 * 60 * 24)
// show what you got
alert( d )
Note:
I find this method safer than Date.parse() as you explicitly specify the date format being input (by splitting into year, month, day in the beginning). This is important to avoid ambiguity when 03/04/2008 could be 3rd of April, 2008 or 4th of March, 2008 depending what country your dates are coming from.

Categories