栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Java静态方法中使用“今天”和“昨天”字符串简化日期对象的替换

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Java静态方法中使用“今天”和“昨天”字符串简化日期对象的替换

您可以通过以下方法使用标准API进行改进:

public static String formatToYesterdayOrToday(String date) throws ParseException {    Date dateTime = new SimpleDateFormat("EEE hh:mma MMM d, yyyy").parse(date);    Calendar calendar = Calendar.getInstance();    calendar.setTime(dateTime);    Calendar today = Calendar.getInstance();    Calendar yesterday = Calendar.getInstance();    yesterday.add(Calendar.DATE, -1);    DateFormat timeFormatter = new SimpleDateFormat("hh:mma");    if (calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {        return "Today " + timeFormatter.format(dateTime);    } else if (calendar.get(Calendar.YEAR) == yesterday.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == yesterday.get(Calendar.DAY_OF_YEAR)) {        return "Yesterday " + timeFormatter.format(dateTime);    } else {        return date;    }}

这是使用Jodatime的方法:

public static String formatToYesterdayOrToday(String date) {    DateTime dateTime = DateTimeFormat.forPattern("EEE hh:mma MMM d, yyyy").parseDateTime(date);    DateTime today = new DateTime();    DateTime yesterday = today.minusDays(1);    DateTimeFormatter timeFormatter = DateTimeFormat.forPattern("hh:mma");    if (dateTime.toLocalDate().equals(today.toLocalDate())) {        return "Today " + timeFormatter.print(dateTime);    } else if (dateTime.toLocalDate().equals(yesterday.toLocalDate())) {        return "Yesterday " + timeFormatter.print(dateTime);    } else {        return date;    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/431141.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号