javaandroidstringdatetimedayofmonth

How to get a specific part of a string in java


I'm developing an Android app that gets the date from the internet. What I have is a complete date format like this one : 2020-06-13T16:21:15.239920+02:00. I want to get the day of the month (which is 13 in this case).


Solution

  • If you are using at least API level 26, then you can use ZonedDateTime class as your string uses the default format that is understood by that class.

    ZonedDateTime zdt = ZonedDateTime.parse("2020-06-13T16:21:15.239920+02:00");
    int d = zdt.getDayOfMonth();
    

    Alternatively, if the format is constant, simply use method substring()

    String dd = "2020-06-13T16:21:15.239920+02:00".substring(8, 10);
    

    If the format is not constant, I would suggest either regular expression or combining ZonedDateTime with DateTimeFormatter