gpt4 book ai didi

java - 从字符串中解析日期

转载 作者:行者123 更新时间:2023-12-01 07:02:56 25 4
gpt4 key购买 nike

我有这样的字符串:

String strDateTimeStamp = "2016-02-29 18:31:51";

现在我想提取它以获得以下格式的结果:

String strYear = "2016";
String strMonth = "02";
String strDate = "29";
String strHour = "18";
String strMinute = "31";
String strSecond = "51";

最佳答案

如果您正在处理日期,则应考虑使用日历:

    String strDateTimeStamp = "2016-02-29 18:31:51";
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = sdf.parse(strDateTimeStamp);
Calendar cal = new Calendar.Builder().setInstant(date).build();

String strYear = Integer.toString(cal.get(Calendar.YEAR));
// Calendar MONTH is starting from 0 we need to add 1
String strMonth = Integer.toString(cal.get(Calendar.MONTH) + 1);
String strDate = Integer.toString(cal.get(Calendar.DATE));

String strHour = Integer.toString(cal.get(Calendar.HOUR_OF_DAY));
String strMinute = Integer.toString(cal.get(Calendar.MINUTE));
String strSecond = Integer.toString(cal.get(Calendar.SECOND));

关于java - 从字符串中解析日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36441504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com