[java] Removing time from a Date object?

I want to remove time from Date object.

DateFormat df;
String date;
df = new SimpleDateFormat("dd/MM/yyyy");
d = eventList.get(0).getStartDate(); // I'm getting the date using this method
date = df.format(d); // Converting date in "dd/MM/yyyy" format

But when I'm converting this date (which is in String format) it is appending time also.

I don't want time at all. What I want is simply "21/03/2012".

This question is related to java datetime date

The answer is


Date dateWithoutTime =
    new Date(myDate.getYear(),myDate.getMonth(),myDate.getDate()) 

This is deprecated, but the fastest way to do it.


You can also manually change the time part of date and format in "dd/mm/yyyy" pattern according to your requirement.

  public static Date getZeroTimeDate(Date changeDate){

        Date returnDate=new Date(changeDate.getTime()-(24*60*60*1000));
        return returnDate;
    }

If the return value is not working then check for the context parameter in web.xml. eg.

   <context-param> 
        <param-name>javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE</param-name>
        <param-value>true</param-value>
    </context-param>

java.util.Date represents a date/time down to milliseconds. You don't have an option but to include a time with it. You could try zeroing out the time, but then timezones and daylight savings will come into play--and that can screw things up down the line (e.g. 21/03/2012 0:00 GMT is 20/03/2012 PDT).

What you might want is a java.sql.Date to represent only the date portion (though internally it still uses ms).


Apache Commons DateUtils has a "truncate" method that I just used to do this and I think it will meet your needs. It's really easy to use:

DateUtils.truncate(dateYouWantToTruncate, Calendar.DAY_OF_MONTH);

DateUtils also has a host of other cool utilities like "isSameDay()" and the like. Check it out it! It might make things easier for you.


You can write that for example:

private Date TruncarFecha(Date fechaParametro) throws ParseException {
    String fecha="";
    DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
    fecha =outputFormatter.format(fechaParametro);
    return outputFormatter.parse(fecha);
}

Don't try to make it hard just follow a simple way

date is a string where your date is saved

String s2=date.substring(0,date.length()-11);

now print the value of s2. it will reduce your string length and you will get only date part.


If you are using Java 8+, use java.time.LocalDate type instead.

LocalDate now = LocalDate.now();
System.out.println(now.toString());

The output:

2019-05-30

https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html


May be the below code may help people who are looking for zeroHour of the day :

    Date todayDate = new Date();
    GregorianCalendar todayDate_G = new GregorianCalendar();
    gcd.setTime(currentDate);
    int _Day    = todayDate_GC.get(GregorianCalendar.DAY_OF_MONTH);
    int _Month  = todayDate_GC.get(GregorianCalendar.MONTH);
    int _Year   = todayDate_GC.get(GregorianCalendar.YEAR);

    GregorianCalendar newDate = new GregorianCalendar(_Year,_Month,_Day,0,0,0);
    zeroHourDate = newDate.getTime();
    long zeroHourDateTime = newDate.getTimeInMillis();

Hope this will be helpful.


In addtition to what @jseals has already said. I think the org.apache.commons.lang.time.DateUtils class is probably what you should be looking at.

It's method : truncate(Date date,int field) worked very well for me.

JavaDocs : https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html#truncate(java.util.Date, int)

Since you needed to truncate all the time fields you can use :

DateUtils.truncate(new Date(),Calendar.DAY_OF_MONTH)

What about this:

    Date today = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    today = sdf.parse(sdf.format(today));

What you want is impossible.

A Date object represents an "absolute" moment in time. You cannot "remove the time part" from it. When you print a Date object directly with System.out.println(date), it will always be formatted in a default format that includes the time. There is nothing you can do to change that.

Instead of somehow trying to use class Date for something that it was not designed for, you should look for another solution. For example, use SimpleDateFormat to format the date in whatever format you want.

The Java date and calendar APIs are unfortunately not the most well-designed classes of the standard Java API. There's a library called Joda-Time which has a much better and more powerful API.

Joda-Time has a number of special classes to support dates, times, periods, durations, etc. If you want to work with just a date without a time, then Joda-Time's LocalDate class would be what you'd use.


A bit of a fudge but you could use java.sql.Date. This only stored the date part and zero based time (midnight)

Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, 2011);
c.set(Calendar.MONTH, 11);
c.set(Calendar.DATE, 5);
java.sql.Date d = new java.sql.Date(c.getTimeInMillis());
System.out.println("date is  " + d);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("formatted date is  " + df.format(d));

gives

date is  2011-12-05
formatted date is  05/12/2011

Or it might be worth creating your own date object which just contains dates and not times. This could wrap java.util.Date and ignore the time parts of it.


String substring(int startIndex, int endIndex)

In other words you know your string will be 10 characers long so you would do:

FinalDate = date.substring(0,9);

You can remove the time part from java.util.Date by setting the hour, minute, second and millisecond values to zero.

import java.util.Calendar;
import java.util.Date;

public class DateUtil {

    public static Date removeTime(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

}

you could try something like this:

import java.text.*;
import java.util.*;
public class DtTime {
public static void main(String args[]) {
String s;
Format formatter;
  Date date = new Date();
  formatter = new SimpleDateFormat("dd/MM/yyyy");
  s = formatter.format(date);
  System.out.println(s);
    }
}

This will give you output as21/03/2012

Or you could try this if you want the output as 21 Mar, 2012

import java.text.*;
import java.util.*;
public class DtTime {
public static void main(String args[]) {
    Date date=new Date();
String df=DateFormat.getDateInstance().format(date);
System.out.println(df);
    }
}

Can't believe no one offered this shitty answer with all the rest of them. It's been deprecated for decades.

@SuppressWarnings("deprecation")
...
    Date hitDate = new Date();
    hitDate.setHours(0);
    hitDate.setMinutes(0);
    hitDate.setSeconds(0);

Another way to work out here is to use java.sql.Date as sql Date doesn't have time associated with it, whereas java.util.Date always have a timestamp. Whats catching point here is java.sql.Date extends java.util.Date, therefore java.util.Date variable can be a reference to java.sql.Date(without time) and to java.util.Date of course(with timestamp).


The correct class to use for a date without time of day is LocalDate. LocalDate is a part of java.time, the modern Java date and time API.

So the best thing you can do is if you can modify the getStartDate method you are using to return a LocalDate:

    DateTimeFormatter dateFormatter = DateTimeFormatter
            .ofLocalizedDate(FormatStyle.SHORT)
            .withLocale(Locale.forLanguageTag("en-IE"));

    LocalDate d = eventList.get(0).getStartDate(); // We’re now getting a LocalDate using this method
    String dateString = d.format(dateFormatter);
    System.out.println(dateString);

Example output:

21/03/2012

If you cannot change the getStartDate, you may still be able to add a new method returning the type that we want. However, if you cannot afford to do that just now, convert the old-fashioned Date that you get (I assume java.util.Date):

    d = eventList.get(0).getStartDate(); // I'm getting the old-fashioned Date using this method
    LocalDate dateWithoutTime = d.toInstant()
            .atZone(ZoneId.of("Asia/Kolkata"))
            .toLocalDate();

Please insert the time zone that was assumed for the Date. You may use ZoneId.systemDefault() for the JVM’s time zone setting, only this setting can be changed at any time from other parts of your program or other programs running in the same JVM.

The java.util.Date class was what we were all using when this question was asked 6 years ago (no, not all; I was, and we were many). java.time came out a couple of years later and has replaced the old Date, Calendar, SimpleDateFormat and DateFormat. Recognizing that they were poorly designed. Furthermore, a Date despite its name cannot represent a date. It’s a point in time. What the other answers do is they round down the time to the start of the day (“midnight”) in the JVM’s default time zone. It doesn’t remove the time of day, only sets it, typically to 00:00. Change your default time zone — as I said, even another program running in the same JVM may do that at any time without notice — and everything will break (often).

Link: Oracle tutorial: Date Time explaining how to use java.time.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?