Write a program to count the number of days between two dates.
The two dates are given as strings, their format is YYYY-MM-DD
as shown in the examples.
Example 1:
Input: date1 = "2019-06-29", date2 = "2019-06-30"
Output: 1
Example 2:
Input: date1 = "2020-01-15", date2 = "2019-12-31"
Output: 15
Approach
Java
public class DaysBetweenTwoDates {public static void main(String[] args) {String date1 = "2019-06-29";String date2 = "2019-06-30";System.out.println(daysBetweenDates(date1, date2));}static boolean isLeap(int n) {if (n % 400 == 0 || n % 100 != 0 && n % 4 == 0)return true;return false;}static int countDays(String dt) {int month[] = { 0, 31, 28, 31, 30, 31, 30,31, 31, 30, 31, 30, 31 };int ye = Integer.parseInt(dt.substring(0, 4));int mo = Integer.parseInt(dt.substring(5, 7));int da = Integer.parseInt(dt.substring(8, 10));int days = 0;for (int i = 1971; i < ye; i++) {days += isLeap(i) ? 366 : 365;}for (int i = 1; i < mo; i++) {if (isLeap(ye) && i == 2) {days += 1;}days += month[i];}days += da;return days;}static int daysBetweenDates(String date1, String date2) {return Math.abs(countDays(date1) - countDays(date2));}}
C++
#include <bits/stdc++.h>using namespace std;bool isLeap(int n){if (n % 400 == 0 || n % 100 != 0 && n % 4 == 0)return true;return false;}int countDays(string dt){int month[13] = {0, 31, 28, 31, 30, 31, 30,31, 31, 30, 31, 30, 31};int ye = stoi(dt.substr(0, 4));int mo = stoi(dt.substr(5, 7));int da = stoi(dt.substr(8, 10));int days = 0;for (int i = 1971; i < ye; i++){days += isLeap(i) ? 366 : 365;}for (int i = 1; i < mo; i++){if (isLeap(ye) and i == 2){days += 1;}days += month[i];}days += da;return days;}int daysBetweenDates(string date1, string date2){return abs(countDays(date1) - countDays(date2));}int main(){string date1 = "2019-06-29";string date2 = "2019-06-30";cout << daysBetweenDates(date1, date2) << "\n";return 0;}
No comments:
Post a Comment