Java 时间戳转换

最近在看 Bob 大叔的《代码整洁之道》,为了在实践中体会,写了一小段代码,功能是进行时间戳转换,第一版完成后根据书中的一些原则重构了下,然后再其中加入了日志记录模块,使用的是 java 自带的 java.util.logging, 主要是看下日志怎么记录,这个过程中也考虑并学习了日志应该记录什么信息,其中还有很多不完善的地方,完整代码如下。

// Main.java
package trans;

import java.util.Scanner;
import java.util.logging.Logger;

public class Main {

    public static void main(String[] args){
        Timestamp ts = new Timestamp();
        ts.initLogger();
        Scanner scanner = new Scanner(System.in);
        final Logger logger = ts.logger;

        while(true) {
            logger.info("Start Choice!");
            System.out.println("******************************");
            System.out.println("Chose from:\n" +
                    "0. Exit\n" +
                    "1. Date transform to timestamp\n" +
                    "2. trans.Timestamp transform to date");
            String choice = scanner.nextLine();
            switch (choice) {
                case "1":
                    System.out.print("Enter Date(format 2020-9-26 11:10:24): ");
                    ts.transDate(scanner, logger);
                    break;
                case "2":
                    System.out.print("Enter trans.Timestamp: ");
                    ts.transStamp(scanner, logger);
                    break;
                case "0":
                    logger.info("Program Exit!");
                    return;
                default:
                    logger.info("Invalid choice, choose again!");
                    break;
            }
            System.out.print("\n\n");
        }
    }
}

// Timestamp.java
package trans;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Timestamp {
    String date;
    long timestamp;
    Logger logger;

    void initLogger(){
        MyLogger logger = new MyLogger("TransDateTimestamp");
        logger.setLoggerLevel(Level.INFO);
        logger.setFileHandler("./Trans" +
                "DateTimstamp.log");
        this.logger = logger.logger;
    }

    void transDate(Scanner scanner, Logger logger){
        try{
            this.date = scanner.nextLine();
            this.timestamp = this.date2stamp(this.date);
            logger.info("Trans successfully!");
            System.out.print("\033[34;1m" + "Date: " + this.date + "\ntrans.Timestamp: "
                    + this.timestamp + "\033[0m");
        } catch (ParseException e) {
            logger.warning("Input Error, Date Format incorrect!");
        }
    }

    long date2stamp(String date) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat();
        dateFormat.applyPattern("yyyy-MM-dd HH:mm:ss");
        Date dateTime = dateFormat.parse(date);
        return dateTime.getTime();
    }

    void transStamp(Scanner scanner, Logger logger){
        try {
            this.timestamp = Long.parseLong(scanner.nextLine());
            this.date = this.stamp2date(this.timestamp);
            logger.info("Trans successfully!");
            System.out.print("\033[34;1m" + "timestamp: " + this.timestamp +"\ndate: "
                    + this.date + "\033[0m");
        }catch(NumberFormatException e){
            logger.warning("Input Error! Timestamp format incorrect!");
        }
    }

    String stamp2date(long timestamp){
        SimpleDateFormat dateFormat = new SimpleDateFormat();
        dateFormat.applyPattern("yyyy-MM-dd HH:mm:ss");
        Date datetime = new Date(timestamp);
        return dateFormat.format(datetime);
    }
}

// MyLogger.java
package trans;

import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.Level;

public class MyLogger {
    Logger logger;

    MyLogger(String loggerName){
        logger = Logger.getLogger(loggerName);
    }

    public void setLoggerLevel(Level level){
        logger.setLevel(level);
    }

    public void setFileHandler(String filePath){
        try{
            FileHandler fileHandler = new FileHandler(filePath);
            logger.addHandler(fileHandler);
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值