dayscott
dayscott

Reputation: 467

Java date function which is not deprecated

I simply need to print the date of the day on the console in this format: Day.Month.Year. Example: 03.10.09

Code:

GregorianCalendar c = new GregorianCalendar();
Date s =  c.getTime(); 
System.out.println(s);

The console prints:

Sat Oct 03 13:33:36 CEST 2009

I could do it with a case statement, but I am sure there is something more elegant, which I simply didn't find.

Upvotes: 1

Views: 1239

Answers (2)

duffymo
duffymo

Reputation: 309008

Use DateFormat and SimpleDateFormat in the java.text package.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class FormatDemo
{

   public static void main(String[] args)
   {
      Calendar c = new GregorianCalendar();
      Date s =  c.getTime();
      DateFormat formatter = new SimpleDateFormat("yyyy-MMM-dd");
      System.out.println(formatter.format(s));
   }
}

Upvotes: 3

waxwing
waxwing

Reputation: 18783

GregorianCalendar c = new GregorianCalendar();
Date s =  c.getTime();
String dateString = new SimpleDateFormat("dd.MM.yy").format(s);
System.out.println(dateString);

Upvotes: 5

Related Questions