基于Java的时间计算程序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于Java的时间计算程序相关的知识,希望对你有一定的参考价值。

在坐火车去学校的途中,突然想着统计下近三十年的日期的星期分布

 

到学校就用Java编写代码

很low的代码

 

首先我的思路是通过时间格式化成月份与日期的结合,如“0904”

然后将其作为数据表的主键,然后再通过设置星期日到星期六最为表的列,初始值均为0,

 

再通过一个子函数来实现插入

插入的思路为先读取,判断当前日期是否为空

如果为空则插入项,如果不为空则当前项在指定星期的天数自加1;

 

思路很清晰,代码也很简单

首先是数据库操作的类;

CalendarDatabase.java

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import java.sql.Connection;

public class CalendarDatabase {
    String createTB = "create table calendarB(" + "mydate varchar(4) primary key," + "Sunday int(4),"
            + "Monday int(4)," + "Tuesday int(4)," + "Wednesday int(4)," + "Thusday int(4)," + "Friday int(4),"
            + "Saturday int(4))";
    String drivers = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/";
    String user = "";
    String password = "";
    String databaseName = "calendarDB";
    String MyWeek[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thusday", "Friday", "Saturday" };
    Connection conn;

    public CalendarDatabase() {
        Statement st = null;
        try {
            Class.forName(drivers);
            conn = DriverManager.getConnection(url, user, password);
            st = conn.createStatement();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (createDatabase(st)) {
            System.out.println("database create succeed");
        } else {
            System.out.println("database exited");
        }
        if (createTable(st, createTB)) {
            System.out.println("table create succeed");
        } else {
            System.out.println("table create failed");
        }
        try {
            st.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void insertOrQuit(String dateStr, int weekIn) {
        String tempSQL = "select " + MyWeek[weekIn] + " from calendarB where mydate=‘" + dateStr + "‘";
        try {
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery(tempSQL);
            if (!rs.next()) {
                st.execute("insert into calendarB values(‘" + dateStr + "‘,1,1,1,1,1,1,1)");
            } else {
                if (rs.getInt(MyWeek[weekIn]) == 1)
                    st.execute("update calendarB set " + MyWeek[weekIn] + "=" + MyWeek[weekIn] + "-1 where mydate=‘"
                            + dateStr + "‘");
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    public void insert(String dateStr, int weekIn) {
        String tempSQL = "select " + MyWeek[weekIn] + " from calendarB where mydate=‘" + dateStr + "‘";
        try {
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery(tempSQL);
            if (!rs.next()) {
                st.execute("insert into calendarB values(‘" + dateStr + "‘,0,0,0,0,0,0,0)");
            } else {
                st.execute("update calendarB set " + MyWeek[weekIn] + "=" + MyWeek[weekIn] + "+1 where mydate=‘"
                        + dateStr + "‘");
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    public boolean createDatabase(Statement st) {
        boolean temp = false;
        String createSQL = "create database " + databaseName;
        try {
            st.execute(createSQL);
            temp = true;
        } catch (Exception e) {
            // TODO: handle exception
            temp = false;
        }
        try {
            st.execute("use " + databaseName);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return temp;
    }

    public boolean createTable(Statement st, String mSql) {
        boolean temp = false;
        try {
            st.execute(mSql);
            temp = true;
        } catch (Exception e) {
            // TODO: handle exception
            temp = false;
        }
        return temp;
    }
}

 


接下来是主程序

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class CalendarSearch {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        CalendarDatabase calendarDatabase=new CalendarDatabase();
        Date date=new Date();
        Calendar calendar=new GregorianCalendar();
        calendar.setTime(date);
        SimpleDateFormat sf=new SimpleDateFormat("MMdd");
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
        long startTime = System.currentTimeMillis();
        while(true) {
            if(sdf.format(date).equals("19900101")) {
                break;
            }
            calendarDatabase.insert(sf.format(date), calendar.get(Calendar.DAY_OF_WEEK)-1);
            calendar.add(calendar.DATE, -1);
            date=calendar.getTime();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("we have spent"+(endTime-startTime)+"ms");
    }
}

 

运行完一个程序需要时间大概为66181ms;

 

运行完的结果很有意思

0229的星期数分布很均匀,都是一天

其他日期的星期数分布也很均匀,绝大多数为4天,少数部分为3天;

 

仔细一想,每年365天,为52个星期多一天,因此如果今年的0904为周一,则去年的0904为周日

而遇到闰年则递推两个,即+1+1+1+2+1+1+1+2,因为周数只有从一到七,循环周期为7,而闰年的循环周期为4

每次循环多出一个1,在相邻闰年的循环过程中3+2+3=8,8-7=1;按照这种计算方法,就是7次一循环,因此日期的周期分布是均等的。

 

以上,是很无聊的程序。


以上是关于基于Java的时间计算程序的主要内容,如果未能解决你的问题,请参考以下文章

如何在片段中使用 GetJsonFromUrlTask​​.java

java代码在片段活动中不起作用

LockSupport.java 中的 FIFO 互斥代码片段

为啥基于锁的程序不能组成正确的线程安全片段?

线程学习知识点总结

计算片段着色器内平面的法线