如何使用Java或Kotlin将指定格式的日期字符串转换为星期几
ISO格式日期字符串转星期几的Java/Kotlin实现方案
刚好之前处理过类似的需求,给你分享两种语言的实现方式,都是基于Java 8+推荐的java.time时间API(线程安全、API更友好,比旧的Date/Calendar好用太多):
Java 实现
直接用java.time包下的类来解析日期并获取星期,代码示例如下:
import java.time.DayOfWeek; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Locale; public class DateWeekConverter { public static void main(String[] args) { // 你的目标日期字符串 String targetDateStr = "2017-03-25T11:24:20"; // 定义ISO标准的日期时间解析器(刚好匹配你给出的格式) DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; // 解析字符串为LocalDateTime对象 LocalDateTime dateTime = LocalDateTime.parse(targetDateStr, formatter); // 获取星期枚举值(比如FRIDAY) DayOfWeek dayOfWeek = dateTime.getDayOfWeek(); // 输出英文星期全称 System.out.println("英文星期:" + dayOfWeek); // 输出中文星期全称,需要指定中文Locale String chineseWeek = dayOfWeek.getDisplayName(java.time.format.TextStyle.FULL, Locale.CHINESE); System.out.println("中文星期:" + chineseWeek); } }
如果需要输出缩写(比如"周五"或者"Fri"),只需要把TextStyle.FULL改成TextStyle.SHORT即可。
Kotlin 实现
Kotlin可以直接复用Java的java.timeAPI,写法更简洁,甚至可以封装成扩展函数让调用更方便:
基础写法
import java.time.DayOfWeek import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.util.Locale fun main() { val targetDateStr = "2020-06-26T11:14:00" val formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME val dateTime = LocalDateTime.parse(targetDateStr, formatter) val dayOfWeek = dateTime.dayOfWeek println("英文星期:$dayOfWeek") val chineseWeek = dayOfWeek.getDisplayName(java.time.format.TextStyle.FULL, Locale.CHINESE) println("中文星期:$chineseWeek") }
优雅的扩展函数写法
如果项目中需要多次转换,可以封装成字符串的扩展函数:
import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.util.Locale fun String.toChineseWeek(): String { val formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME val dateTime = LocalDateTime.parse(this, formatter) return dateTime.dayOfWeek.getDisplayName(java.time.format.TextStyle.FULL, Locale.CHINESE) } // 调用示例 fun main() { val dateStr = "2017-03-25T11:24:20" println("转换后的中文星期:${dateStr.toChineseWeek()}") }
兼容低版本Java的说明
如果你的项目还在使用Java 7及以下,可以使用Joda-Time库来实现,但官方已经停止维护Joda-Time了,推荐尽量升级到Java 8+使用java.timeAPI。
内容的提问来源于stack exchange,提问作者U wan
相关产品推荐
相关产品推荐

