$show=/label

Kotlin Program To Convert String to Date

SHARE:

A quick guide to converting a string to date in kotlin using predefined formats custom formats. Examples program for covnerting several string dates to Date objects.

1. Introduction


In this article, you'll learn how to convert String to Date in Kotlin. The string can be any valid date format but you should convert the String date format to an actual date object.

Example: 

String = "2020-05-01";
Converted Date: 2020-05-01 

A converted date is in a form of the Date object.

This is part of the Kotin Programming Series.


Kotlin Program To Convert String to Date



2.  Kotlin - Convert String to Date using Predefined Built-in Patterns


[package com.javaprogramto.kotlin.stringtodate
import java.time.LocalDate
import java.time.format.DateTimeFormatter
fun main() {
var dateInString = "2020-05-02" var simpleFormat = DateTimeFormatter.ISO_DATE;
var convertedDate = LocalDate.parse(dateInString, simpleFormat)
println("String to Date converted : $convertedDate")
}]

Output:

[String to Date converted : 2020-05-02]

In the above program first created String that stores the data value and created a default simple date format DateTimeFormatter.ISO_DATE that takes the data in formats "YYYY-MM-DD" or "YYYY-MM-DD+HH:SS".

LocalDate.parse() method takes two values and those are date in the string and the format.

Finally, the parse() method returns a LocalDate object that will have the same value of the string date.

3. Kotlin - Convert String to Date Other Formats using Predefined Formats


In the above program, you have seen converting a string to date in the same format. But, you will see the conversion from one format string to a different date format.

Example to covert "YYYY-MM-DD+HH:SS" to "YYYY-MM-DD".

[var dateInString1 = "2020-12-03+01:00";
var simpleFormat2 = DateTimeFormatter.ISO_DATE;
var output = LocalDate.parse(dateInString1, simpleFormat2)
println("output : "+output)]

Output:

[output : 2020-12-03]

4. Kotlin - Convert String to Date Using Custom Pattern Formatters


There is another way to do convert string to date using custom patterns. Always dates will not be in predefined formats provided in DateTimeFormatter class.

Sometimes, you will be needed for different date formats are in a string. You should tell to the parse() method what is the string date format. Otherwise, we will get an exception.

[package com.javaprogramto.kotlin.dates.stringtodate
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.*
fun main() {
val string = "May 31, 2020"

val formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy", Locale.ENGLISH)
val date = LocalDate.parse(string, formatter)
println("Date in format of MMM dd, yyyy is $date")
}]

Output:

[Formated Date object is 2020-05-31]

5. Kotlin Date Format Exceptions


As a result, If you pass incorrect date formates to the parse() method then it will throw DateTimeParseException.

 Support/IntelliJIdea2019.2/Kotlin/kotlinc/lib/kotlin-stdlib.jar:/Users/venkateshn/Library/Application Support/IntelliJIdea2019.2/Kotlin/kotlinc/lib/kotlin-reflect.jar:/Users/venkateshn/Library/Application Support/IntelliJIdea2019.2/Kotlin/kotlinc/lib/kotlin-test.jar" com.javaprogramto.kotlin.stringtodate.KotlinStringToDateKt
Exception in thread "main" java.time.format.DateTimeParseException: Text '2020=05-02' could not be parsed at index 4

 at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)

 at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)

 at java.time.LocalDate.parse(LocalDate.java:400)

 at com.javaprogramto.kotlin.stringtodate.KotlinStringToDateKt.main(KotlinStringToDate.kt:12)

 at com.javaprogramto.kotlin.stringtodate.KotlinStringToDateKt.main(KotlinStringToDate.kt)


Process finished with exit code 1

Exception 2:

Exception in thread "main" java.time.format.DateTimeParseException: Text 'May 31, 2020' could not be parsed, unparsed text found at index 10

 at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1952)

 at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)

 at java.time.LocalDate.parse(LocalDate.java:400)

 at com.javaprogramto.kotlin.dates.stringtodate.KotlinStringToDateCustomFormatsKt.main(KotlinStringToDateCustomFormats.kt:14)

 at com.javaprogramto.kotlin.dates.stringtodate.KotlinStringToDateCustomFormatsKt.main(KotlinStringToDateCustomFormats.kt)

6. Conclusion


In conclusion, you've seen how to convert string to date in kotlin using predefined formats and custom formats.

All the code is shown in this article is over GitHub.

You can download the project directly and can run in your local without any errors.



If you have any queries please post in the comment section.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,16,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,23,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,84,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,13,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,10,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,78,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,93,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Matrix,5,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,23,String,58,String Programs,12,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Kotlin Program To Convert String to Date
Kotlin Program To Convert String to Date
A quick guide to converting a string to date in kotlin using predefined formats custom formats. Examples program for covnerting several string dates to Date objects.
https://1.bp.blogspot.com/-3XSlxGYyM6w/XqptfAFDatI/AAAAAAAAClg/VDdZvDIOy-QckLSAmlHFo4lTh2l2xnNDQCLcBGAsYHQ/s640/Kotlin%2BProgram%2BTo%2BConvert%2BString%2Bto%2BDate-min.png
https://1.bp.blogspot.com/-3XSlxGYyM6w/XqptfAFDatI/AAAAAAAAClg/VDdZvDIOy-QckLSAmlHFo4lTh2l2xnNDQCLcBGAsYHQ/s72-c/Kotlin%2BProgram%2BTo%2BConvert%2BString%2Bto%2BDate-min.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/04/kotlin-program-convert-string-to-date.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/04/kotlin-program-convert-string-to-date.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content