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.
ruby
# With timezone info
puts Time.parse('2008-05-06 13:29')
java
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = df.parse("2008-05-06 13:29");
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
DateTime dt = fmt.parseDateTime("2008-05-06 13:29");
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
# 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";
groovy
def date = new SimpleDateFormat("yyy-MM-dd HH:mm").parse("2008-05-06 13:29")
def date = Date.parse("yyy-MM-dd HH:mm", "2008-05-06 13:29")
scala
val date = new SimpleDateFormat("yyy-MM-dd HH:mm").parse("2008-05-06 13:29")
python
import time
time.strptime("2008-05-06 13:29", "%Y-%m-%d %H:%M")
cpp
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"));
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);
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"))
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())
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")),
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 *)
}
csharp
DateTime parsedDate = DateTime.Parse("2008-05-06 13:29");
// Ideally, you would catch the potential FormatException or use DateTime.TryParse in production code.
php
echo date("jS F, Y g:i:sa", strtotime("2008-05-06 13:29")); // small version
clojure
(.. (SimpleDateFormat. "yyyy-MM-dd HH:mm")
(parse "2008-05-06 13:29"))
fantom
dt := DateTime.fromLocale("2008-05-06 13:29", "YYYY-MM-DD hh:mm")
go
t, err := time.Parse("2006-01-02 15:04", "2008-05-06 13:29")
if err == nil {
fmt.Println(t)
}

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.
ruby
require 'date'

next_week = Date.today + 8

puts next_week.day # day of month
puts next_week.yday # day of year
puts next_week.strftime('%B') # month name
puts next_week.strftime('%A') # day name
java
Calendar cal = Calendar.getInstance();
cal.add(DAY_OF_YEAR, 8);
System.out.println(cal.get(DAY_OF_MONTH));
System.out.println(cal.get(DAY_OF_YEAR));
System.out.println(new SimpleDateFormat("MMMM").format(cal.getTime()));
System.out.println(new SimpleDateFormat("EEEE").format(cal.getTime()));
perl
#! /usr/bin/perl
# -*- Mode: CPerl -*-

use strict;
use Date::Calc qw(:all);

my $days_in_future = $ARGV[0];
$days_in_future = 8 unless $days_in_future;

my ($year,$month,$day, $hour,$min,$sec, $doy,$dow,$dst) = Localtime();

my ($fyear,$fmonth,$fday) = Add_Delta_Days($year,$month,$day,$days_in_future);

printf "Now: %d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d\n",
$year,$month,$day,$hour,$min,$sec;

printf "Then: %d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d\n",
$fyear,$fmonth,$fday,$hour,$min,$sec;

printf "Then: day of month: %d\n",$fday;
printf "Then: day of year: %d\n",Day_of_Year($fyear,$fmonth,$fday);
printf "Then: day of name: %s\n",
Day_of_Week_to_Text(Day_of_Week($fyear,$fmonth,$fday));
printf "Then: month name: %s\n",Month_to_Text($fmonth);

#eos
use Time::Piece;
use Time::Seconds;

my $t = localtime;
my $t_8 = $t + (ONE_DAY * 8);

printf "Now: %d, %d, %s, %s\n",
$t->day_of_month, $t->day_of_year, $t->fullmonth, $t->fullday;

printf "Then: %d, %d, %s, %s\n",
$t_8->day_of_month, $t_8->day_of_year, $t_8->fullmonth, $t_8->fullday;
groovy
use (TimeCategory) {
eight_days_time = 1.week.from.now + 1.day
}
println eight_days_time[DAY_OF_MONTH]
println eight_days_time.format('d') // alternative to above
println eight_days_time[DAY_OF_YEAR]
println eight_days_time.format('MMMM')
println eight_days_time.format('EEEE')
scala
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)
python
from datetime import datetime, timedelta

eightDaysFromNow = datetime.now() + timedelta(days=8)

print eightDaysFromNow.strftime('%d') # day of month
print eightDaysFromNow.strftime('%j') # day of year
print eightDaysFromNow.strftime('%B') # month name FULL
print eightDaysFromNow.strftime('%A') # day of week name FULL
cpp
QDate dateEightDaysFromNow = QDate::currentDate().addDays(8);
fsharp
Using F# interactive

> let Then = DateTime.Now.AddDays(8.0)
- let dayNumber = Then.DayOfYear.ToString()
- let solution = Then.ToString("dd " + dayNumber + " MMMM dddd");;

val Then : DateTime = 08/08/2010 08:58:05
val dayNumber : string = "220"
val solution : string = "08 220 August Sunday"

>
ocaml
let days = [| "Sunday"; "Monday"; "Tuesday"; "Wednesday"; "Thursday"; "Friday"; "Saturday" |]
let months = [| "January"; "February"; "March"; "April"; "May"; "June"; "July"; "August"; "September"; "October"; "November"; "December" |]

let current_time = Unix.time () in
let one_day = 86400. (* seconds *) in
let future_time = Unix.localtime (current_time +. 8. *. one_day) in
Printf.printf "day of month = %d, day of year = %d, month name = %s, day name = %s\n"
future_time.Unix.tm_mday
future_time.Unix.tm_yday
months.(future_time.Unix.tm_mon)
days.(future_time.Unix.tm_wday)
csharp
DateTime date = DateTime.Today.AddDays(8);

Console.WriteLine("Day of month: " + date.Day);
Console.WriteLine("Day of year: " + date.DayOfYear);
Console.WriteLine("Month name: " + date.ToString("MMMM"));
Console.WriteLine("Day name: " + date.ToString("dddd"));

// The two ToString calls will use the current locale.
// To get localised month and day names, see http://msdn.microsoft.com/en-us/library/8tfzyc64.aspx
php
$eightdays = strtotime("+8 days");

$dayofmonth = date("d", $eightdays); // 3
$dayofyear = date("z", $eightdays); // 183
$monthname = date("F", $eightdays); // July
$dayname = date("l", $eightdays); // Saturday
$eightdays = time() + 1 * 60 * 60 * 24 * 8;

$dayofmonth = date("d", $eightdays); // 3
$dayofyear = date("z", $eightdays); // 183
$monthname = date("F", $eightdays); // July
$dayname = date("l", $eightdays); // Saturday
clojure
(let [cal (Calendar/getInstance)]
(.add cal Calendar/DAY_OF_YEAR 8)
(println (.format (SimpleDateFormat. "d, D, MMMM, EEEE")
(.getTime cal))))
fantom
date := Date.today + 8day
echo(date.day)
echo(date.dayOfYear)
echo(date.month.localeFull)
echo(date.weekday.localeFull)
go
t := time.Now().Add(8 * 24 * time.Hour)
fmt.Println(t.Day())
// no day of year
fmt.Println(t.Month())
fmt.Println(t.Weekday())

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.)
java
Calendar cal = Calendar.getInstance();
cal.set(2009, Calendar.JANUARY, 1);
Locale[] locales = { ENGLISH, FRENCH, ITALIAN, GERMAN, new Locale("nl") };

for (Locale l : locales) {
System.out.println(getDateInstance(FULL, l).format(cal.getTime()));
}
perl
#!/usr/bin/perl
use warnings;
use strict;

use locale;
use POSIX qw(strftime);
use Time::Local;

my $date=timegm(0,0,0, 1,0,101); #00:00:00 01/01/2001

my $str_time = strftime "%c", gmtime;

print "Date: $str_time\n";
groovy
cal = Calendar.instance
cal.set(2009, JANUARY, 1)
[ENGLISH, FRENCH, ITALIAN, GERMAN, new Locale('nl')].each { lang ->
println getDateInstance(FULL, lang).format(cal.time)
}

// relies on Java I18N capabilities which supports many locales, see:
// http://java.sun.com/javase/technologies/core/basic/intl/
// available Locales may depend on your version of Java and/or
// operating system and/or installed fonts
scala
val date = new GregorianCalendar(2009, JANUARY, 1).getTime
val locales = List(ENGLISH, FRENCH, ITALIAN, GERMAN, new Locale("nl"))
println(locales.map{getDateInstance(FULL, _).format(date)}.mkString("\n"))
python
from datetime import datetime
from locale import setlocale, LC_TIME

now = datetime(2009, 1, 1)

locales = ('en_us', 'fr_fr', 'it_it', 'de_de', 'nl_nl')
for locale in locales:
setlocale(LC_TIME, locale)
print now.strftime('%A, %B %d %Y')

cpp
QList<QLocale::Language> locales;
locales << QLocale::English
<< QLocale::French
<< QLocale::German
<< QLocale::Italian
<< QLocale::Dutch;

QDate date(2009, 1, 1);
foreach (QLocale::Language ll, locales)
{
QLocale::setDefault(ll);
qDebug() << date.toString(Qt::DefaultLocaleLongDate);
}
fsharp
open System
open System.Globalization

let jan1 = DateTime(2009, 1, 1)

[ "en-US"; "fr-FR"; "de-DE"; "it-IT"; "nl-NL" ]
|> List.map CultureInfo.CreateSpecificCulture
|> List.map (fun c -> jan1.ToString("D", c))
|> List.iter (printfn "%s")
csharp
using System.Globalization;

DateTime newYearsDay = new DateTime(2009, 1, 1);
CultureInfo[] locales = {
CultureInfo.CreateSpecificCulture("en-US"),
CultureInfo.CreateSpecificCulture("fr-FR"),
CultureInfo.CreateSpecificCulture("de-DE"),
CultureInfo.CreateSpecificCulture("it-IT"),
CultureInfo.CreateSpecificCulture("nl-NL")
};

foreach (CultureInfo locale in locales)
{
Console.WriteLine(newYearsDay.ToString("D", locale));
}
php
/* Be aware of that you need to have the locales installed */
setlocale(LC_TIME, "en_US");
echo strftime("%A, %B %e, %Y%n"); // %n = \n in strftime()
setlocale(LC_TIME, "fr_FR"); // French
echo strftime("%A, %B %e, %Y%n");
setlocale(LC_TIME, "de_DE"); // German
echo strftime("%A, %B %e, %Y%n");
setlocale(LC_TIME, "it_IT"); // Italian
echo strftime("%A, %B %e, %Y%n");
setlocale(LC_TIME, "nl_NL", "nld_nld"); // Dutch; Unix and Windows
echo strftime("%A, %B %e, %Y%n");
$locales = array("en_US", "fr_FR", "de_DE", "nl_NL", "it_IT");
foreach ($locales as $locale) {
setlocale(LC_TIME, $locale);
echo strftime("%A, %B %d %Y%n");
}
clojure
(let [time (.getTime (GregorianCalendar. 2009 Calendar/JANUARY 1))]
(doseq [locale ["en" "fr" "it" "de" "nl"]]
(println (.format (DateFormat/getDateInstance DateFormat/FULL
(Locale. locale))
time))))
fantom
// May require modification of Fantom distribution t
// for undefined locales - basically just create a '<locale-name>.props' plain text file with values like this:
// sunAbbr=Sun
// ..
// sunFull=Sunday
["en", "fr", "ru"].map { Locale(it) }.each |Locale l| {
l.use { echo(Date(2009, Month.jan, 1).toLocale("WWWW, MMMM D, YYYY")) }
}

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.
ruby
puts DateTime.now
java
import java.util.Date;

public class SolutionXX {
public static void main(String[] args) {
Date now = new Date();
System.out.println(now.toString());
}
}
perl
use Class::Date;
my $date = Class::Date->now();
print $date->string()."\n";

print localtime()."\n";
use Time::Piece ();

# Date object
my $date = Time::Piece::localtime;
print "$date\n";
# no object
print scalar(localtime),"\n";
groovy
println new Date()
scala
println(new java.util.Date)
python
from datetime import datetime
print datetime.utcnow()
cpp
QDate now = QDate::currentData();
qDebug() << now.toString();
time_t date = time(0);
cout << ctime(&date);
fsharp
printfn "%A" System.DateTime.Now
erlang
io:format("~p~n", [calendar:local_time()])
ocaml
Unix.localtime (Unix.gettimeofday ())
csharp
// Creating a variable first:
DateTime now = DateTime.Now;
Console.WriteLine(now);

// Without creating a variable:
Console.WriteLine(DateTime.Now);
php
echo date('r') . "\n";
$d = new DateTime();
echo $d->format('r') . "\n";
haskell
import System.Time

main = do ct <- getClockTime
print ct
import Data.Time

main = do zt <- getZonedTime
print zt
clojure
(import 'java.util.Date)

(println (str (Date.)))
fantom
echo(DateTime.now)
go
fmt.Println(time.Now())