Arun
Arun

Reputation: 9

Get current date as string in databricks using scala

I want to get current date in Scala as a String. For example, today current date is 5th Jan. I want to store it as a new variable dynamically as below.

val currdate : String = “20220105”

When I am using val currdate = Calendar.getInstance.getTime then am not getting output in desired format as above.

Upvotes: 0

Views: 1936

Answers (2)

jwvh
jwvh

Reputation: 51271

This is how it's done using the contemporary java.time library.

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

val currdate: String = 
  LocalDate.now.format(DateTimeFormatter.ofPattern("yyyyMMdd"))

Older utilities like Calendar and SimpleDate still work (mostly) but should be avoided.

Upvotes: 2

gatear
gatear

Reputation: 946

Why do you need it as String?
For a Spark query you could use java.sql.Timestamp directly.

This how you get it:

import java.sql.Timestamp
import java.text.SimpleDateFormat
import java.time.Instant

val now: Timestamp =
  Timestamp.from(Instant.now())

If you really want a formatted String:

val asString =
  new SimpleDateFormat("yyyyMMdd").format(now)

SimpleDateFormat is old and not thread-safe but should do the job.

Upvotes: 0

Related Questions