Java.SimpleDateFormat.Date.getTime.setTime.Format

本文介绍如何使用Java的SimpleDateFormat类解析和格式化日期时间字符串,包括将字符串转换为Date对象,获取毫秒值,并设置Date对象的时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可以使用 `java.text.SimpleDateFormat` 类来将字符串类型的时间转换成 `java.util.Date` 类型,并使用 `java.util.Calendar` 类来实现时间的加减操作,以下是将字符串 "10" 加上 10 分钟的示例代码: ```java import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateExample { public static void main(String[] args) throws ParseException { // 定义时间格式 SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); // 将字符串转换成 Date 类型 Date date = sdf.parse("10:00:00"); // 使用 Calendar 类来实现时间的加减操作 Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.MINUTE, 10); Date newDate = calendar.getTime(); // 将新的日期转换成字符串 String newDateString = sdf.format(newDate); // 输出结果 System.out.println("原时间:" + sdf.format(date)); System.out.println("加上10分钟后的时间:" + newDateString); } } ``` 在这个示例代码中,我们首先定义了时间格式为 "HH:mm:ss" 的 `SimpleDateFormat` 对象 `sdf`,然后使用 `sdf.parse()` 方法将字符串 "10:00:00" 转换成 `java.util.Date` 类型的时间 `date`。接着,我们使用 `Calendar.getInstance()` 方法创建一个 `Calendar` 对象 `calendar`,并将 `date` 设置为 `calendar` 的时间。然后,我们使用 `calendar.add()` 方法将时间加上 10 分钟,并使用 `calendar.getTime()` 方法将 `calendar` 转换成 `java.util.Date` 类型的时间 `newDate`。最后,我们使用 `sdf.format()` 方法将 `newDate` 转换成字符串类型的时间 `newDateString`,并输出结果。 需要注意的是,这个示例代码中使用的时间格式为 "HH:mm:ss",如果需要使用其他的时间格式,需要相应地修改 `SimpleDateFormat` 对象的格式。另外,这里的时间加减操作是以分钟为单位,如果需要以其他的时间单位进行加减操作,需要调用相应的 `Calendar` 方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值