Date Formatting

Sat 28 July 2018, in category Date and Time

date, format

Date formatting allows you to change how a given date is displayed for readability purposes or comply with standards like ISO 8601. Here are various examples that show how to format the date: July 22nd, 2018.

Java

LocalDate myDate = LocalDate.of(2018, 7, 22);

String[] formats = {
        "MMMM dd, YYYY", // July 22, 2018
        "MMM dd YYYY",   // Jul 22 2018
        "EEEE, MMMM dd, YYYY", // Sunday, July 22, 2018
        "MM/dd/YYYY", // 07/22/2018
        "dd/MM/YYYY", // 22/07/2018
        "MMMM dd, YYYY 'is the' DDD 'day of the year'"  // July 22, 2018 is the 203 day of the year
};

for(String fmt : formats){
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(fmt);
    System.out.println(myDate.format(formatter));
}

System.out.println(myDate.format(DateTimeFormatter.BASIC_ISO_DATE));  // 20180722

C#

DateTime myDate = new DateTime(2018, 7, 22);

String[] formats = {
    "MMMM dd, yyyy",  // July 22, 2018
    "MMM dd yyyy",  //Jul 22 2018
    "dddd, MMMM dd, yyyy", // Sunday, July 22, 2018
    "D", // Sunday, July 22, 2018
    "MM/dd/yyyy",  // 07/22/2018
    "d",           // 7/22/2018
    "dd/MM/yyyy",  // 22/07/2018
    "M",           // July 22
    "Y",           // July, 2018
};

foreach (var fmt in formats) {
    Console.WriteLine(myDate.ToString(fmt));
}

Console.WriteLine(myDate.ToString("MMMM dd, yyyy") 
                  + " is the " + myDate.DayOfYear 
                  + " day of the year");  // July 22, 2018 is the 203 day of the year 

Python

my_date = date(2018, 7, 22)

fmts = [
  '%B %d, %Y',  # July 22, 2018
  '%b %d %Y',   # Jul 22 2018
  '%A, %B %d, %Y', # Sunday, July 22, 2018
  '%m/%d/%Y',   # 07/22/2018
  '%d/%m/%Y',   # 22/07/2018
  '%B %d, %Y is the %j day of the year', # July 22, 2018 is the 203 day of the year
]

for fmt in fmts:
  print(my_date.strftime(fmt))

JavaScript

// This example requires the Moment library
const moment = require('moment');
let myDate = moment('2018-07-22');

var formats = [
  'MMMM DD, YYYY',  // July 22, 2018
  'MMMM Do, YYYY',  // July 22nd, 2018
  'MMM DD YYYY',    // Jul 22 2018
  'dddd, MMMM DD, YYYY',  // Sunday, July 22, 2018
  'MM/DD/YYYY',      // 07/22/2018
  'DD/MM/YYYY',      // 22/07/2018
  'MMMM DD, YYYY [is the] DDD [day of the year]'  // July 22, 2018 is the 203 day of the year
]

formats.forEach(function(item, index, array){
  console.log(myDate.format(item));
});

Go

// Go has a unique way to format dates using a reference date of Mon Jan 2 15:04:05 MST 2006
t := time.Date(2018,7,22,0,0,0,0, time.UTC)

var fmts [5]string
fmts[0] = "January 2, 2006"
fmts[1] = "Jan 2 2006"
fmts[2] = "Monday, January 2, 2006"
fmts[3] = "01/02/2006"
fmts[4] = "02/01/2006"

for _, element := range fmts {
    fmt.Println(t.Format(element))
}