简体   繁体   English

从字符串解析日期

[英]Parse a date from a string

I have String like this: 我有这样的字符串:

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

Now I would like to extract it to get result in a below format: 现在,我想提取它以获得以下格式的结果:

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

If you are working with dates you should consider using Calendar : 如果您使用日期,则应考虑使用Calendar:

    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));

All of the Answers using java.util.Date and java.text.DateFormat / .SimpleDateFormat are outmoded. 使用java.util.Datejava.text.DateFormat / .SimpleDateFormat所有答案均已过时。 Those old date-time classes are poorly designed, confusing, and troublesome. 这些旧的日期时间类设计不良,令人困惑且麻烦。 Avoid them. 避免他们。

java.time java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 A vast improvement over the old date-time classes. 与旧的日期时间类相比有了很大的改进。

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use… ). 大部分的java.time功能后移植到Java 6和7 ThreeTen,反向移植 ,并进一步适应的AndroidThreeTenABP (见如何使用...... )。

First, replace the SPACE in the middle of your input string with a T to conform with the ISO 8601 standard. 首先,将输入字符串中间的SPACE替换为T以符合ISO 8601标准。 These standard formats are used by default in the java.time classes when parsing/generating strings. 解析/生成字符串时,java.time类中默认使用这些标准格式。

String input = "2016-02-29 18:31:51".replace( " " , "T" );

Parse as a LocalDateTime . 解析为LocalDateTime The “Local” means not associated with any time zone. “本地”表示不与任何时区关联。 So this is not an actual moment on the timeline. 因此,这不是时间表上的实际时刻。 But apparently not an issue in the context of this Question. 但显然在本课题中不是问题。

LocalDateTime ldt = LocalDateTime.parse( input );

Now you can ask for your various pieces as needed by calling the various getter methods. 现在,您可以通过调用各种getter方法来索要各种组件。 These methods return an int primitive which you can, of course, convert to String values. 这些方法返回一个int 原语 ,您当然可以将其转换为String值。

You can do like this by splitting your String 您可以通过拆分String来做到这一点

String[] splittedString = strDateTimeStamp.split("-|:|\\s");

String strYear = splittedString[0];
String strMonth = splittedString[1];
String strDate = splittedString[2];
String strHour = splittedString[3];
String strMinute = splittedString[4];
String strSecond = splittedString[5];

First split string using split(" ") on the basis of space ..it will give you a array of string of length 2 . 首先在空格..的基础上使用split(" ")分割字符串,它将为您提供长度为2的字符串数组。 which contains (2016-03-04) and (16:32:33) . 其中包含(2016-03-04)(16:32:33) Then split both string againg using split("-") and split(":") reapectively . 然后分别使用split("-")split(":")再次分割两个字符串。 you will get your answer. 您将得到答案。 Please try code at your own may better to you. 请尝试自己编写代码可能对您更好。

Try This.. 尝试这个..

    String CurrentString = "2016-02-29 18:31:51";
    String[] separated = CurrentString.split(" ");
    String date = separated[0];
    String time = separated[1];
    String[] separated_date = date.split("-");
    String[] separated_time = time.split(":");
    String strYear = separated_date[0];
    String strMonth = separated_date[1];
    String strDate = separated_date[2];
    String strHour = separated_time[0];
    String strMinute = separated_time[1];
    String strSecond = separated_time[2];

I suggest to use regex with a pattern like "[- :]" 我建议将正则表达式“ [-:]”等模式一起使用

Example: 例:

public static void main(String[] args) {
    String strDateTimeStamp = "2016-02-29 18:31:51";
    String[] solution = strDateTimeStamp.split("[- :]");
    for (int i = 0; i < solution.length; i++) {
        System.out.println(solution[i]);
    }
}

this will generate an array with all the elements you need 这将生成包含您需要的所有元素的数组

  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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM