как создать код JavaScript для объекта date сегодня + 11 дней в JavaScript Shopify - PullRequest
0 голосов
/ 01 марта 2019

Я хочу добавить дату в html в shopify описание продукта

Что бы он сказал

Мы отправим товар с сегодняшнего дня + 11 дней .....

И если он выпадает на субботу или воскресенье, он будет перенесен на понедельник, потому что мы закрыты в субботу или воскресенье.

Код пока такой, но не знаю, как переместить его в первый понедельник, если необходимо

// 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>

Но что-то не так со сценарием

Ответы [ 4 ]

0 голосов
/ 01 марта 2019

momentJS.Проверьте это.Позволяет вам играть с датами в здравом уме.Имеет плагины для таких вещей, как запрос на nextBusinessDay () и многое другое.

Не возитесь с датами и ванильным Javascript, если только вы не являетесь программистом Javascript.Это отстой, и момент существует по уважительной причине.Меньше сосать.

0 голосов
/ 01 марта 2019

// 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>
0 голосов
/ 01 марта 2019

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>
0 голосов
/ 01 марта 2019

Это на самом деле не так уж сложно.Объект Date предоставляет функцию getDay () , которая возвращает день недели.Это целое число от 0 до 6.

Вы можете сделать это следующим образом:

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();

В блоке переключателей, где обрабатываются субботы и воскресенья и просто добавляется один или два дня к дате.

Кстати, в вашем коде есть некоторые опечатки.В конце оператора должен быть ; , а не ,

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...