jonprasetyo
jonprasetyo

Reputation: 3586

Possible to remove the time and just want the date from getTime() Date class?

Is it possible to remove the day (Fri), the time (22:34:21) and the time zone (GMT) by just having an output like "Jan 11 1980" instead of "Fri Jan 11 22:34:21 GMT 1980"??

Code below:

Calendar date = Calendar.getInstance();
date.set(Calendar.YEAR, 1980);
date.set(Calendar.MONTH, 0);
date.set(Calendar.DAY_OF_MONTH, 11);

Date dob = date.getTime();

System.out.println(dob);//Fri Jan 11 22:34:21 GMT 1980

Many thanks!

Upvotes: 1

Views: 331

Answers (6)

user000001
user000001

Reputation: 33367

Date date = new Date(); 
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy"); 
System.out.println(sdf.format(date)); 

Output:

Feb 26 2013

If you want a specific date, do

Calendar c = Calendar.getInstance();
c.set(1980, 0, 11);
Date date = c.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy");
System.out.println(sdf.format(date));

Prints

Jan 11 1980

Upvotes: 7

MadProgrammer
MadProgrammer

Reputation: 347314

Date is a representation of the number of milliseconds since the epoch (January 1, 1970, 00:00:00 GMT)

In order to "remove" the time portion of a Date, you will want to use a DateFormat

Something as simple as;

System.out.println(new SimpleDateFormat("dd/MM/yyyy").format(dob));

Should work.

For a more localised version, you should use DateFormat.getDateInstance()

System.out.println(DateFormat.getDateInstance().format(dob));
System.out.println(DateFormat.getDateInstance(DateFormat.SHORT).format(dob));
System.out.println(DateFormat.getDateInstance(DateFormat.MEDIUM).format(dob));
System.out.println(DateFormat.getDateInstance(DateFormat.LONG).format(dob));

Upvotes: 1

Terry Li
Terry Li

Reputation: 17268

public class DateFormat {
    public static void main(String[] args) {
        Calendar date = Calendar.getInstance();
        date.set(Calendar.YEAR, 1980);
        date.set(Calendar.MONTH, 0);
        date.set(Calendar.DAY_OF_MONTH, 11);
        Date dob = date.getTime();
        System.out.println(new SimpleDateFormat("MMM dd yyyy").format(dob));
    }
}

Output:

Jan 11 1980

Upvotes: 2

tmwanik
tmwanik

Reputation: 1661

SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy");

System.out.println(sdf.format(dob));

Upvotes: 0

RudolphEst
RudolphEst

Reputation: 1250

DateFormat dateFormatter = DateFormat.getDateInstance();
System.out.println(dateFormatter.format(date);

This will print the only the date corresponding to your current system locale settings.

See also: DateFormat in the JavaDoc

Upvotes: 0

Wasafa1
Wasafa1

Reputation: 805

you can use:

stringToPrint = time.getMonth()+" "+time.getDate()+" "+time.getYear();

for more info: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.html

Upvotes: -1

Related Questions