关于java:将日期转换为天 | 珊瑚贝

Convert date into days

本问题已经有最佳答案,请猛点这里访问。


如何将以下格式的日期转换为分钟、小时、天、周。一般使用这个信息来显示消息发布信息。

2020-04-11T17:41:00Z

  • 分钟等是什么意思?您想获取特定单位的部分日期或日期吗?
  • 这里有很多帖子可以回答您的问题(stackoverflow.com/questions/4216745/…)。
  • 我想这样显示…………如果日期是 15 分钟前到当前时间……我必须显示”15 分钟前”……如果日期是 1 天前……我必须显示”1 天前”。
  • DateTimeFormatter.ISO_DATE_TIME.parse(data).get(ChronoField.??DAY_OF_MONTH)
  • 欢迎来到 SO 社区,T 和 00Z 是什么?
  • @Zain 格式是 ISO 8601,它定义了 T 和 Z 以及字符串中的所有内容。
  • @OleV.V.多谢兄弟 :)


你的问题不是很清楚。所以,我在这里写一些示例代码供您理解。正如您在此示例中所见,您将进一步探索 java.time。和 java.time.format。与日期和时间相关的类非常丰富。避免使用过时的 java.util.* 日期和时间 API。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String str =“2020-04-11T17:41:00”;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“yyyy-MM-dd’T’HH:mm:ss”);
        LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
        System.out.println(“Year:” + dateTime.getYear());
        System.out.println(“Month:” + dateTime.getMonthValue());
        System.out.println(“Day:” + dateTime.getDayOfMonth());
        System.out.println(“Hour:” + dateTime.getHour());
        System.out.println(“Minute:” + dateTime.getMinute());
    }
}

输出:

1
2
3
4
5
Year: 2020
Month: 4
Day: 11
Hour: 17
Minute: 41

不太清楚你的意思,所以我会在这个前提下工作。输入此格式的字符串:2020-04-11T17:41:00Z。至于将其转换为分钟、小时等的意思。我假设将其转换为日期对象?如果我错了请纠正我

小提示:如果您是日期格式的控制者,在转换为该字符串之前,我建议您使用 Unix 时间(A.K.A. POSIX 时间 – 在线阅读)。

如果我的解释是正确的,你可以使用 SimpleDateFormat

1
2
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-ddThh:mm:ssZ”);
Date dt = sdf.parse(string);

您还可以使用 sdf 将您的日期对象转换为您的给定格式:

1
sdf.format(YourDateObject)
  • 请不要教年轻人使用早已过时且臭名昭著的麻烦 SimpleDateFormat 类。至少不是第一选择。而且不是没有任何保留。今天,我们在 java.time、现代 Java 日期和时间 API 及其 DateTimeFormatter 方面有了更好的表现。您的代码也会抛出 java.lang.IllegalArgumentException: Illegal pattern character ‘T’。


考虑使用 Joda Time 库,它很受欢迎,很多人都在使用它,因为它很简单。

它有你需要的自定义类型。乔达网站

他们网站上的示例代码:

1
2
3
4
5
6
public boolean isAfterPayDay(DateTime datetime) {
  if (datetime.getMonthOfYear() == 2) {   // February is month 2!!
    return datetime.getDayOfMonth() > 26;
  }
  return datetime.getDayOfMonth() > 28;
}
  • 由于 Joda Time 的大部分功能都添加到 Java 8 中,因此 Joda Time 网站建议迁移到该功能。 (据我了解,它可能更加标准,保证在不添加任何依赖项的情况下可用,因此对于大多数用途来说是一个更好的选择。)


来源:https://www.codenong.com/61163613/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_8933.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?