View Category

Parse a date and time from a string

Given the string "2008-05-06 13:29", parse it as a date representing 6th March, 2008 1:29:00pm in the local time zone.
val date = new SimpleDateFormat("yyy-MM-dd HH:mm").parse("2008-05-06 13:29")
import scala.util.parsing.combinator.RegexParsers
import java.util.{GregorianCalendar, Date}

class DateParser extends RegexParsers {

val fd = """\d{4}""".r
val td = """\d{2}""".r

def parseDate: Parser[Date] =
year ~ ("-" ~> other) ~ ("-" ~> other) ~ other ~ (":" ~> other) ^^ {
case y ~ mo ~ d ~ h ~ mi => (new GregorianCalendar(y, mo - 1, d, h, mi)).getTime

def year: Parser[Int] = fd ^^ { _.toInt }
def other: Parser[Int] = td ^^ { _.toInt }


Display information about a date

Display the day of month, day of year, month name and day name of the day 8 days from now.
import java.util.Calendar
import java.text.SimpleDateFormat

val formatString = "d, D, MMMM, EEEE"
val cal = Calendar.getInstance

cal.add(Calendar.DAY_OF_YEAR, 8)

println(new SimpleDateFormat(formatString) format cal.getTime)

Display a date in different locales

Display a language/locale friendly version of New Year's Day for 2009 for several languages/locales. E.g. for languages English, French, German, Italian, Dutch the output might be something like:

Thursday, January 1, 2009
jeudi 1 janvier 2009
giovedì 1 gennaio 2009
Donnerstag, 1. Januar 2009
donderdag 1 januari 2009

(Indicate in comments where possible if any language specific or operating system configuration needs to be in place.)
val date = new GregorianCalendar(2009, JANUARY, 1).getTime
val locales = List(ENGLISH, FRENCH, ITALIAN, GERMAN, new Locale("nl"))
println({getDateInstance(FULL, _).format(date)}.mkString("\n"))

Display the current date and time

Create a Date object representing the current date and time. Print it out.
If you can also do this without creating a Date object you can show that too.
println(new java.util.Date)