06 August 2017

JAVA: Số ngày khoảng cách giữa hai mốc thời gian trong ngôn ngữ Java

package com.giaima;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class DateDiff {
 public static void main(String[] args) {
  // set the new date format
  DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

  //Date currentDate = new Date();
        //PLus 24h
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.HOUR, 24);

  Date date1 = null;
  Date date2 = null;

  try {
   // calculating the difference b/w startDate and endDate
   String startDate = "2017-07-12 20:40:00";
   String endDate = simpleDateFormat.format(currentDate);

   date1 = simpleDateFormat.parse(startDate);
   date2 = simpleDateFormat.parse(endDate);

   long getDiff = date2.getTime() - date1.getTime();

   // using TimeUnit class from java.util.concurrent package
   long getDaysDiff = TimeUnit.MILLISECONDS.toDays(getDiff);

   System.out.println("Differance between date " + startDate + " and " + endDate + " is " + getDaysDiff + " days.");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}
Output:
Differance between date 2017-07-12 20:40:00 and 2017-08-07 00:12:44 is 25 days.
24 hours = 1 day
60 minutes = 1 hour
60 seconds = 1 minute
1000 milliseconds = 1 second
package com.giaima;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDiff {
 public static void main(String[] args) {

  DateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");

  Date currentDate = new Date();
  Date date1 = null;
  Date date2 = null;

  try {
   String startDate = "01-01-2016";
   String endDate = simpleDateFormat.format(currentDate);

   date1 = simpleDateFormat.parse(startDate);
   date2 = simpleDateFormat.parse(endDate);

   long getDiff = date2.getTime() - date1.getTime();

   long getDaysDiff = getDiff / (24 * 60 * 60 * 1000);

   System.out.println("Differance between date " + startDate + " and " + endDate + " is " + getDaysDiff + " days.");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}
Output:
Differance between date 01-01-2016 and 26-12-2016 is 360 days.

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang