Converting Strings to Dates in Spark

In this blog, we will be going over spark functions used to format dates, change their format, and also convert strings to date. So let us get started.

to_date – Convert String to Date

First we will see how we can convert normal date to string. We can use to_Date function for this.

It is simple right? But what will happen if our date is not in same format as “yyyy-MM-dd”? Let us see output of such code.

Oh, we are getting null. This is because spark is not able to understand our date string. To overcome this, we can specify the format for our date. to_date function accepts optional parameter as a format for the date.

format_with_to_date
Format with to_date function

Spark supported simple date format used in Java language

Spark Facts

So we are able to let spark know the format of our date and spark picked our date correctly this time. hurry!!

Changing Format of Date in Spark

We now our date is correct but we do not want this “yyyy-MM-dd” format. We want in “dd/MM/yyyy” format for some reason. We can do that as well. We can convert our date format easily.

As we can see, using date_format function we can change the format of date too as per our requirement.

If you want to find out more of date functions, you can read blog Date functions in Spark.

I hope you found this useful. See you in the next blog.

Similar Posts

Leave a Reply

Your email address will not be published.