Convert String to Date Using Predefined Formatters

thumbnail

In this tutorial, we’ll be taking tutorial about how to convert string to date format. First, we have to know about the date pattern. Okay, now let’s explore some of the more commonly used options:

Letter

Date Component

Example

d

day

28; Fri

M

Month

09; Dec

y

year

19

H

hour

18

m

minute

17

The number of character within the String used will give different output that returned by the date component. For example, let’s take the month of September. If we defined the date string as

“MM”

Then it will give result the number code – 09. However, if we add an extra M to our date string:

“MMM”

Then the result that appear will be the word Sep.

Now lets get back to our kotlin program. In this program, you’ll learn to convert string to date in Kotlin formatter.

Example 1: Convert String to Date using predefined formatters

import java.time.LocalDate
import java.time.format.DateTimeFormatter

fun main(args: Array<String>){
    val dateString1 = "2019-09-28"
    val dateFormat1 = LocalDate.parse(dateString1, DateTimeFormatter.ISO_DATE)
    println("ISO_DATE: "+dateFormat1)
}

When you run the program, the output will be:

ISO_DATE: 2019-09-28

As you can see from the above code, we’ve used the predefined formatter ISO_DATE. The format takes date string in the format 2019-09-28 or 2019-09-28+18:28’. The LocalDate’s parse() function parses the given string using the given formatter.

You can also remove the ISO_DATE formatter and replace the parse() method with:

LocalDate date = LocalDate.parse(string, DateTimeFormatter);

Another example is to use BASIC_ISO_DATE. The format takes date string in the format 20190928.

import java.time.LocalDate
import java.time.format.DateTimeFormatter

fun main(args: Array<String>){
    val dateString2 = "20190928"
    val dateFormat2 = LocalDate.parse(dateString2, DateTimeFormatter.BASIC_ISO_DATE)
    println("BASIC_ISO_DATE: "+dateFormat2)
}

The output will be:

BASIC_ISO_DATE: 2019-09-28

So that’s all for converting string to date using predefined formatters. For another tutorial, you can find it more in this website.

Back To Top