基於Java的時間計算程式

來源:互聯網
上載者:User

標籤:tuesday   color   set   通過   遞推   quit   fail   orm   統計   

在坐火車去學校的途中,突然想著統計下近三十年的日期的星期分布

 

到學校就用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的時間計算程式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.