Scala “string to date” and “date to string” methods

Here are a couple of “string to date” and “date to string” methods. They’re written in Scala, but are easily converted to Java. They only use the Java Date and SimpleDateFormat classes:

import java.text.SimpleDateFormat
import java.util.Date

object Utils {

    val DATE_FORMAT = "EEE, MMM dd, yyyy h:mm a"

    def getDateAsString(d: Date): String = {
        val dateFormat = new SimpleDateFormat(DATE_FORMAT)
        dateFormat.format(d)
    }

    def convertStringToDate(s: String): Date = {
        val dateFormat = new SimpleDateFormat(DATE_FORMAT)
        dateFormat.parse(s)
    }

}

While I’m in the neighborhood, here are two more Scala methods to convert from Date to Long, and Long to Date:

def convertDateStringToLong(dateAsString: String): Long = {
    Utils.convertStringToDate(dateAsString).getTime
}

def convertLongToDate(l: Long): Date = new Date(l)