calculate difference between two dates in year javascript

javaScript Difference Between Two Dates in Years Months Days

In this javascript Tutorial, Calculate the difference between two dates in years, months, and days javascript. Here, we will explain how to calculate the difference between two dates and get the difference in years, months and days.

JavaScript Difference Between Two Dates in Years Months Days

  • javascript difference between two dates in the year
  • calculate the difference between two dates in month javascript
  • javascript difference between two dates in days
  • javascript difference between two dates in years months days

1. javascript difference between two dates in year

Here, we will create a javascript, which is used to calculate the difference between two dates in year.

Use the given below function, To calculate the difference between 2 dates and get the difference year.

Ex:-

          

Result Of the above code is: 1 Year

2. Calculate the difference between two dates in Month javascript

Here, we will create a javascript, which is used to calculate the difference between two dates in month.

Use the given below function, To calculate the difference between 2 dates and get difference month.

function monthDiff(dt1, dt2) < var diffMonth =(dt2.getTime() - dt1.getTime()) / 1000; diffMonth /= (60 * 60 * 24 * 7 * 4); return Math.abs(Math.round(diff)); >

Ex:-

          

Result Of the above code is: 5 Month

Читайте также:  Python наследование переопределение init

3. javascript difference between two dates in days

Here, we will create a javascript that is used to calculate the difference between two dates in days.

Use the given below function, To calculate the difference between 2 dates and get difference days.

Ex:-

          

Result Of the above code is: 2 days

4. javascript difference between two dates in years months days

javascript difference between two dates in years months days. Here we will create a new function, which is used to calculate the difference between two dates in years, months and days.

Using the below-given function, we will calculate the difference between two dates and get years, months and days between two dates:

function diff_year_month_day(dt1, dt2) < var time =(dt2.getTime() - dt1.getTime()) / 1000; var year = Math.abs(Math.round((time/(60 * 60 * 24))/365.25)); var month = Math.abs(Math.round(time/(60 * 60 * 24 * 7 * 4))); var days = Math.abs(Math.round(time/(3600 * 24))); return "Year :- " + year + " Month :- " + month + " Days :-" + days; >

Ex:-

          

Result of above code is: Year :- 1 Month :- 18 Days :-517

If you want to know more about javascript date and time methods, you may like following date and time methods:

You may like

  1. javascript Convert Hours to Minutes,Minutes to Seconds,date to Milliseconds
  2. Compare two dates with JavaScript – Examples
  3. JavaScript Get Month Name With Various Examples
  4. Get Month 2 Digits in JavaScript
  5. javaScript Get Current Year 2 and 4 Digit – Example
  6. Get Current Date Time javaScript
  7. JavaScript: Date setUTCDate() Method
  8. Set UTC Month In javaScript
  9. setUTCFullYear() Method JavaScript With Examples
  10. javascript date setUTCHours() Method With Examples
  11. JavaScript: d.setUTCMinutes() Method e.g.
  12. setUTCSecond() Method By JavaScript
  13. javaScript Date set UTC milliseconds
  14. setUTCSecond() Method By JavaScript
  15. JavaScript: Date.getUTCDate() Method
  16. getUTCmonth Method javaScript With Example
  17. Digital Clock with date in javaScript
  18. JavaScript: Set Date Methods
  19. JavaScript Get Date Methods

If you have any questions or thoughts to share, use the comment form below to reach us.

Author Admin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Источник

Каким образом посчитать разность дат в JS?

Всем привет,
Имеется простая таблица с графами Дата начала работ и Запланированная дата сдачи
Данные вводятся в модальном окне.
Дата начала работ имеет input date.
Запланированная дата сдачи имеет input number.
В базе данных mold_start_date и mold_scheduled_date имеют тип date.
В модальном окне собираются данные формы и отправляются в БД по принципу:

public function addMolds()< $mold_start_date = $_POST['mold_start_date']; // первая дата $mold_scheduled_date = $_POST['mold_scheduled_date']; //вторая дата $mold_scheduled_date = date( "Y-m-d", strtotime( $mold_start_date."+".$mold_scheduled_date." days") );//первая дата + вторая дата с преобразованием в тип даты MySQL $insertQuery = "INSERT INTO ".$this->moldTable." (mold_start_date, mold_scheduled_date) VALUES ('".$_POST["mold_start_date"]."', '".$mold_scheduled_date."')"; $isUpdated = mysqli_query($this->dbConnect, $insertQuery); >

Теперь эти данные нужно изменить, опять же в модальном окне и отправить на сервер используя UPDATE вместо INSERT.

public function updateMolds()< if($_POST['moldId']) < $mold_start_date = $_POST['mold_start_date']; $mold_scheduled_date = $_POST['mold_scheduled_date']; $mold_scheduled_date = date( "Y-m-d", strtotime( $mold_start_date."+".$mold_scheduled_date." days") ); $updateQuery = "UPDATE ".$this->moldTable." SET mold_start_date = '".$_POST["mold_start_date"]."', '".$mold_scheduled_date."' WHERE "; $isUpdated = mysqli_query($this->dbConnect, $updateQuery); > >

Данные в модальное окно подставляются с помощью JS

$("#moldsList").on('click', '.update', function()< var moldId = $(this).attr("id"); var action = 'getMolds'; $.ajax(< url:'moldsaction.php', method:"POST", data:, dataType:"json", success:function(data) Изменить форму"); $('#action').val('updateMolds'); $('#save').val('Save'); > >) >);

Все данные отлично добавляются, но не изменяются, потому что прежде чем выводить в модальное окно, данные дату нужно снова посчитать, но в обратном порядке: Запланированная дата сдачи — Дата начала работ и вывести уже число. Каким образом посчитать в разницу в датах в JS и подставить в модальное окно?

Источник

Оцените статью