广告
返回顶部
首页 > 资讯 > 后端开发 > JAVA >总结java 字符串,日期类Date和 Calendar相互转化,以及相关常用方法
  • 268
分享到

总结java 字符串,日期类Date和 Calendar相互转化,以及相关常用方法

java开发语言 2023-10-21 18:10:00 268人浏览 八月长安
摘要

Java中,可以通过以下方法将字符串转换为Date: String dateString = "2023-07-28";DateFORMat format = new SimpleDateFormat

Java中,可以通过以下方法将字符串转换为Date:

String dateString = "2023-07-28";DateFORMat format = new SimpleDateFormat("yyyy-MM-dd");Date date = format.parse(dateString);

在这个例子中,我们将一个字符串类型的日期转换为Date对象。需要注意的是,我们需要使用SimpleDateFormat类来指定日期格式。
同样地,我们也可以将Date转换为字符串:

Date date = new Date();DateFormat format = new SimpleDateFormat("yyyy-MM-dd");String dateString = format.format(date);

Java中,可以通过以下方法将Date转换为Calendar:

Date date = new Date();Calendar calendar = Calendar.getInstance();calendar.setTime(date);

在这个例子中,我们将当前时间的Date对象转换为Calendar对象。需要注意的是,我们需要使用Calendar.getInstance()方法来获取一个Calendar实例。

同样地,我们也可以将Calendar转换为Date:

Calendar calendar = Calendar.getInstance();Date date = calendar.getTime();

在这个例子中,我们将当前时间的Calendar对象转换为Date对象。需要注意的是,我们需要使用Calendar.getTime()方法来获取一个Date实例。

除了转换之外,Date和Calendar类还有许多常用的方法。以下是一些常见的方法:
Date类方法
getTime():返回自1970年1月1日00:00:00 GMT以来的毫秒数。
toString():返回一个表示此日期的字符串。
before(Date when):如果此日期在when之前,则返回true。
after(Date when):如果此日期在when之后,则返回true。
Calendar类方法
get(int field):返回给定日历字段的值。
set(int field, int value):将给定日历字段设置为给定值。
add(int field, int amount):将给定的时间量添加到给定的日历字段中。
getTime():返回一个表示此Calendar时间值(从历元到现在的毫秒偏移量)的Date对象。
toString():返回一个表示此Calendar时间值(从历元到现在的毫秒偏移量)的字符串表示形式

来源地址:https://blog.csdn.net/weixin_44728473/article/details/131980626

--结束END--

本文标题: 总结java 字符串,日期类Date和 Calendar相互转化,以及相关常用方法

本文链接: https://www.lsjlt.com/news/434023.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作