Parse string with integer value to date

前端 未结 4 1154
梦毁少年i
梦毁少年i 2021-01-15 21:37

I have a string with this value, for example: \"20130211154717\" I want it to be like \"2013-02-11 15:47:17\". How can I do that?

相关标签:
4条回答
  • 2021-01-15 22:18

    You can use the substring() method to get what you want:

    String data = "20130211154717";
    String year = data.substring(0, 4);
    String month = data.substring(4, 2);
    // etc.
    

    and then string them together:

    String formatted = year + "-" + month + "-" + . . .
    
    0 讨论(0)
  • 2021-01-15 22:26

    You can use regular expressions for that:

    String formattedDate = plainDate.replaceFirst(
            "(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})",
            "$1-$2-$3 $4:$5:$6");
    

    Though, I like assylias's SimpleDateFormat answer better. :-)

    0 讨论(0)
  • 2021-01-15 22:34

    What you want to use for this is a SimpleDateFormat. It has a method called parse()

    0 讨论(0)
  • 2021-01-15 22:37

    You can use two SimpleDateFormat: one to parse the input and one to produce the output:

    String input =  "20130211154717";
    Date d = new SimpleDateFormat("yyyyMMddhhmmss").parse(input);
    String output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(d);
    System.out.println("output = " + output);
    
    0 讨论(0)
提交回复
热议问题