You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Scala中获取如20180122_101043的无空格时间戳字符串?

获取指定格式的当前时间字符串

嗨,既然你已经拿到了Calendar.getInstance()的实例,接下来只需要用日期格式化工具把它转换成你要的格式就行啦,具体步骤如下:

  1. 创建日期格式化器:使用SimpleDateFormat类,传入你需要的格式字符串"yyyyMMdd_HHmmss"——这里的每个占位符对应时间的不同部分:

    • yyyy:四位年份(比如2018)
    • MM:两位月份(比如01)
    • dd:两位日期(比如22)
    • HH:24小时制的两位小时(比如10)
    • mm:两位分钟(比如10)
    • ss:两位秒数(比如43)
  2. 格式化Calendar对象:调用格式化器的format()方法,传入cal.getTime()把Calendar转换成Date对象即可得到目标字符串。

完整的代码示例:

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

public class TimeExample {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        // 指定目标格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        // 格式化时间
        String formattedTime = sdf.format(cal.getTime());
        // 输出结果:比如20180122_101043
        System.out.println(formattedTime);
    }
}

额外提醒(Java 8+推荐)

如果你的项目是Java 8及以上版本,更推荐使用java.time包下的新API,因为SimpleDateFormat不是线程安全的,在多线程环境下容易出问题。用DateTimeFormatter的写法如下:

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

public class TimeExampleJava8 {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
        String formattedTime = now.format(formatter);
        System.out.println(formattedTime);
    }
}

这个写法更简洁,而且线程安全,是现在的最佳实践哦~

内容的提问来源于stack exchange,提问作者osk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:58:20