View Problem

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.
ExpandDiskEdit
ruby
# With timezone info
puts Time.parse('2008-05-06 13:29')
ExpandDiskEdit
java
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = df.parse("2008-05-06 13:29");
ExpandDiskEdit
java JodaTime
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
DateTime dt = fmt.parseDateTime("2008-05-06 13:29");
DiskEdit
perl
#! /usr/bin/perl
# -*- Mode: CPerl -*-

use strict;
use POSIX;

# 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.

my $ds = "2008-05-06 13:29";

my $y;
my $m;
my $d;
my $hr;
my $mn;

print "Original: ",$ds,"\n";

if ( $ds =~ /(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})/ ){
$y = $1 - 1900;
$m = $2;
$d = $3;
$hr = $4;
$mn = $5;

printf "Nominal: %s\n",
strftime("%e %B, %Y %l:%M:%S%P",0, $mn , $hr, $d, $m,$y);

my $eth = "";
if ( $d == 1 ){
$eth = "st";
} elsif ( $d == 2 ){
$eth = "nd";
} elsif ( $d == 3 ){
$eth = "rd";
} else {
$eth = "th";
}

printf "As required: %d%s %s\n",$d,$eth,
strftime("%B, %Y %l:%M:%S%P",0, $mn , $hr, $d, $m,$y);
}

#eos
DiskEdit
perl 5.10+
# Shurely you mean 6th MAY? If not, oh well
use Time::Piece;

my $dt_str = '2008-05-06 13:29';
my $tp = Time::Piece->strptime( $dt_str, '%Y-%m-%d %H:%M');
print $tp,"\n";
ExpandDiskEdit
groovy
def date = new SimpleDateFormat("yyy-MM-dd HH:mm").parse("2008-05-06 13:29")
DiskEdit
groovy
def date = Date.parse("yyy-MM-dd HH:mm", "2008-05-06 13:29")
ExpandDiskEdit
scala
val date = new SimpleDateFormat("yyy-MM-dd HH:mm").parse("2008-05-06 13:29")
DiskEdit
scala 2.11.5
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 }

}
DiskEdit
python
import time
time.strptime("2008-05-06 13:29", "%Y-%m-%d %H:%M")
ExpandDiskEdit
cpp C++/CLI .NET 2.0
DateTimeOffset^ dateTime = DateTimeOffset::Parse("2008-05-06 13:29");

// Use format specifiers to appropriately format string
// 1. Default culture
Console::WriteLine("{0}", dateTime->ToString("d MMMM, yyyy h:mm:sstt"));

// 2. Nominated culture
Console::WriteLine("{0}", dateTime->ToString("d MMMM, yyyy h:mm:sstt"), Globalization::CultureInfo::CreateSpecificCulture("en-us"));
ExpandDiskEdit
cpp C++/CLI .NET 2.0
DateTimeOffset^ dateTime = DateTimeOffset::Parse("2008-05-06 13:29");

// Customize date/time string
Text::StringBuilder^ dsb = gcnew Text::StringBuilder(40);
dsb->Append(dateTime->ToString("%d"))->Append("th ")->Append(dateTime->ToString("MMMM, yyyy h:mm:ss"))->Append(dateTime->ToString("tt")->ToLower());

Console::WriteLine("{0}", dsb);
ExpandDiskEdit
fsharp
let dateTime = DateTimeOffset.Parse("2008-05-06 13:29")

// Use format specifiers to appropriately format string
// 1. Default culture
printfn "%s" (dateTime.ToString("d MMMM, yyyy h:mm:sstt"))

// 2. Nominated culture
Console.WriteLine("{0}", dateTime.ToString("d MMMM, yyyy h:mm:sstt"), Globalization.CultureInfo.CreateSpecificCulture("en-us"))
ExpandDiskEdit
fsharp
let dateTime = DateTimeOffset.Parse("2008-05-06 13:29")

// Customize date/time string
let dsb = ((new StringBuilder(40)).Append(dateTime.ToString("%d")).Append("th ").Append(dateTime.ToString("MMMM, yyyy h:mm:ss")).Append(dateTime.ToString("tt").ToLower()))

printfn "%s" (dsb.ToString())
ExpandDiskEdit
erlang
% AFAIK, no datetime-parsing library exists; 'parse_to_datetime' is a simplistic, problem-specific hack
LocalDateTime = erlang:universaltime_to_localtime(parse_to_datetime("2008-05-06 13:29:34")),
DiskEdit
ocaml
let s = "2008-05-06 13:29" in
let r = Str.regexp "\\([0-9][0-9][0-9][0-9]\\)-\\([0-9][0-9]\\)-\\([0-9][0-9]\\) \\([0-9][0-9]\\):\\([0-9][0-9]\\)" in
assert (Str.string_match r s 0);
Unix.mktime { Unix.tm_sec = 0;
tm_min = int_of_string (Str.matched_group 5 s);
tm_hour = int_of_string (Str.matched_group 4 s);
tm_mday = int_of_string (Str.matched_group 3 s);
tm_mon = int_of_string (Str.matched_group 2 s) - 1;
tm_year = int_of_string (Str.matched_group 1 s) - 1900;
tm_wday = -1;
tm_yday = -1;
tm_isdst = true; (** Daylight time savings in effect *)
}
DiskEdit
csharp
DateTime parsedDate = DateTime.Parse("2008-05-06 13:29");
// Ideally, you would catch the potential FormatException or use DateTime.TryParse in production code.
ExpandDiskEdit
php
echo date("jS F, Y g:i:sa", strtotime("2008-05-06 13:29")); // small version
DiskEdit
haskell
import Data.Time

main = print (parseTimeOrError True defaultTimeLocale "%Y-%m-%d %H:%M" "2008-05-06 13:29" :: UTCTime)
ExpandDiskEdit
clojure
(.. (SimpleDateFormat. "yyyy-MM-dd HH:mm")
(parse "2008-05-06 13:29"))
ExpandDiskEdit
fantom
dt := DateTime.fromLocale("2008-05-06 13:29", "YYYY-MM-DD hh:mm")
ExpandDiskEdit
go
t, err := time.Parse("2006-01-02 15:04", "2008-05-06 13:29")
if err == nil {
fmt.Println(t)
}

Submit a new solution for ruby, java, perl, groovy ...