使用 netbeans java 计算 mysql 数据库中存储的日期与当前日期之间的天数

Count days between dates stored in mysql database and current date with netbeans java

我需要计算两个日期之间的天数差..第一个日期应该是当前日期,下一个日期已经在 Mysql 数据库中搜索过..

Mysql存储日期的日期格式为yyyy-MM-dd

我只是通过文本字段获取了存储的日期 所以请帮我解决这个问题!

java.time

如果您将日期存储为文本,请解析为 LocalDate

LocalDate localDate = LocalDate.parse( input ) ;

如果您更恰当地将日期存储在类似于 SQL-标准 DATE 类型的列中,则检索为 LocalDate.

LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;

捕获某个特定地区(时区)人们使用的挂钟时间中显示的当前日期。

ZoneId z = ZoneId.of( "America/Montreal" ) ;

LocalDate today = LocalDate.now( z ) ;

计算以天为单位的跳跃时间。

long days = ChronoUnit.DAYS.between( localDate , today ) ;

提示:要表示日期范围,一对 LocalDate 对象,添加 ThreeTen-Extra library to your project. Use the LocalDateRange class。

LocalDateRange range = LocalDateRange.of( localDate , today ) ;

关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

您可以直接与数据库交换 java.time 对象。使用 JDBC driver compliant with JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* classes.

从哪里获得java.time classes?

ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

 private void CountDaysActionPerformed(java.awt.event.ActionEvent evt) {                                          

        //check your zone Id and place it on the double quote 
        ZoneId z=ZoneId.of("Asia/Colombo");
        LocalDate today=LocalDate.now(z);

        String currentDate=today.toString();

        SimpleDateFormat myformat=new SimpleDateFormat("yyyy-MM-dd");

        String firstDate1 =jTextField1.getText();
        String secondDate1 =currentDate;

        try{

            Date firstDate = myformat.parse(firstDate1);
            Date secondDate = myformat.parse(secondDate1);

            long dif = secondDate.getTime()- firstDate.getTime();

            int daysBetween =(int) (dif/(1000*60*60*24));


            //answer wil be the difference between your current date and the date you provided in the jTextField1
            System.out.println(daysBetween);


        }catch(Exception e){
            e.printStackTrace();
        }


    }