Java 获取当前时间并转换为16进制字符串

本文介绍使用 Java 获取当前时间并将其转换为16进制字符串的代码示例。

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Etest {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern('yyMMddHHmmss'));
        int hex = Integer.parseInt(format, 16);
        String hexString = String.format('%06X', hex);
        System.out.println(hexString);
    }
}

该程序的功能是:

  1. 使用 LocalDateTime.now() 获取当前时间。
  2. 使用 DateTimeFormatter.ofPattern('yyMMddHHmmss') 将当前时间格式化为字符串,格式为'yyMMddHHmmss'。
  3. 使用 Integer.parseInt(format, 16) 将格式化后的字符串转换为16进制整数。
  4. 使用 String.format('%06X', hex) 将16进制整数转换为6位16进制字符串,不足6位前面补0。
  5. 使用 System.out.println(hexString) 打印输出转换后的16进制字符串。

该程序运行正常,没有错误。

Java 获取当前时间并转换为16进制字符串

原文地址: https://www.cveoy.top/t/topic/n9sq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录