java.util.Date does not have a Timezone. It is not aware of TimeZone.

When you print, java picks up the default time zone.

Conceptually, you cannot have a date time without timezone. A date time has to be in one and only one zone. You may convert it to other zones, but it can never be without a zone.

If your business use case requires awareness of Time Zone, I would prefer to use Calendar class, or Joda Time. Avoid playing with Date class. If your business use cases do not require any time zone awareness, then go ahead with date. Assume all Date instances are in your default time zone.

Best thing is to use Calendar (or Joda Time). Calendar is a bit unintuitive but you will be able to get your job done. It is not without reason that Date class is mostly deprecated.

Initialize your Calendar with Timezone (check out available constructors). Use Dateformat to convert and show in UI in whatever time zone you wish to. I posted some code in your previous question. That might help you. I was stuck in a similar problem. I have dates in the DB in one time zone. To display them in another time zone on UI, you need to convert that datetime to another zone.

Answer from RuntimeException on Stack Overflow
Top answer
1 of 1
6

UPDATE: Added Joda-Time version, since question was changed from java-8 to jodatime.


If you have a Joda-Time DateTime, then use toLocalDate() and toLocalDateTime(...):

DateTime dateTime = new DateTime(2018, 1, 1, 14, 13, 04, 574);
System.out.println(dateTime);
LocalDate localDate = dateTime.toLocalDate();
System.out.println(localDate);
LocalDateTime localDateTime = localDate.toLocalDateTime(LocalTime.MIDNIGHT);
System.out.println(localDateTime);
2018-01-01T14:13:04.574-05:00
2018-01-01
2018-01-01T00:00:00.000

If you have "a Date get from Database", i.e. a java.sql.Date, then use toLocalDate() and atStartOfDay():

java.sql.Date sqlDate = new java.sql.Date(118, 0, 1);
System.out.println(sqlDate);
LocalDate localDate = sqlDate.toLocalDate();
System.out.println(localDate);
LocalDateTime localDateTime = localDate.atStartOfDay();
System.out.println(localDateTime);
2018-01-01
2018-01-01
2018-01-01T00:00

If you have a java.sql.Timestamp, use toLocalDateTime() and truncatedTo(...):

java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(118, 0, 1, 14, 13, 04, 574000000);
System.out.println(sqlTimestamp);
LocalDateTime localDateTime = sqlTimestamp.toLocalDateTime();
System.out.println(localDateTime);
localDateTime = localDateTime.truncatedTo(ChronoUnit.DAYS);
System.out.println(localDateTime);
2018-01-01 14:13:04.574
2018-01-01T14:13:04.574
2018-01-01T00:00

If you have a java.util.Date, use toInstant(), atZone(...), toLocalDate(), and atStartOfDay():

java.util.Date utilDate = new java.util.Date(118, 0, 1, 14, 13, 04);
System.out.println(utilDate);
Instant instant = utilDate.toInstant();
System.out.println(instant);
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
System.out.println(zonedDateTime);
LocalDateTime localDateTime = zonedDateTime.toLocalDate().atStartOfDay();
System.out.println(localDateTime);
Mon Jan 01 14:13:04 EST 2018
2018-01-01T19:13:04Z
2018-01-01T14:13:04-05:00[America/New_York]
2018-01-01T00:00
🌐
Java2s
java2s.com › Tutorials › Java › Data_Type_How_to › Legacy_Date_Time › Remove_time_from_a_Date_object.htm
Java Data Type How to - Remove time from a Date object
Date Timezone · double · enum · float · integer · Legacy Date · Legacy Date Format · Legacy Date Time · long · number format · String · Back to Legacy Date Time ↑ · We would like to know how to remove time from a Date object. import java.text.DateFormat; import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; //from www.
Top answer
1 of 2
12

The accepted Answer is working too hard. Manipulating offsets is the province of a date-time library. Doing such work yourself is a waste of your time, and likely to be a source of bugs.

The old java.util.Date/.Calendar classes are notoriously troublesome. Avoid them. Instead use either java.time or Joda-Time.

java.time

Java 8 and later has a new java.time framework built-in.

Confused Question

Your Question is confused. You say you want to ignore time zone, yet you accept an answer that does indeed parse and process the time zone. And that answer then adjusts the result by an offset. So, it seems that you do not want to ignore the time zone.

Indeed, ignoring the time zone rarely makes sense. Perhaps you want to compare a pair of factories in Berlin and in Detroit to see if they both take a lunch break at the same time. In this case you are comparing their respective wall-clock time. The java.time framework offers the “Local” classes for this purpose: LocalDate, LocalTime, and LocalDateTime. But this is rarely needed in most business scenarios in my experience. These objects are not tied to the timeline.

So it seems that what you do want is to be able to compare date-time values across various time zones. The java.time classes do that implicitly. ZonedDateTime objects with various assigned time zones can be compared to one another with isBefore, isAfter, and isEqual methods.

Example Code

First we parse the input string.

The z pattern code means to expect and parse a time zone. The resulting date-time object will also be assigned this object if no other specific time zone is specified.

We also assign a Locale object with a human language component matching the text we expect to see in the input string. In this case, we need any Locale with English.

String input = "Oct 04, 2015 2:11:58,757 AM UTC";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MMM dd, yyyy K:mm:ss,SSS a z" ).withLocale( Locale.ENGLISH );

ZonedDateTime then = ZonedDateTime.parse( input, formatter );

Next we get the current time for Québec. This arbitrary choice of time zone will demonstrate further below that we can compare this ZonedDateTime object to another with a different time zone. Specifically, comparing against the UTC time zone assigned to our then object above.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now( zoneId );

Do the comparison.

Boolean isThenBeforeNow = then.isBefore( now );

By the way, generally-speaking, the best practice in date-time work is to convert all your date-time values to UTC time zone for business logic, storage, and data exchange. Adjust into a time zone only as need be to satisfy a user’s expectations on-screen or in reports.

ZonedDateTime nowUtc = now.withZoneSameInstant( ZoneOffset.UTC );

Dump to console.

System.out.println( "input: " + input );
System.out.println( "then: " + then );
System.out.println( "now: " + now );
System.out.println( "isThenBeforeNow: " + isThenBeforeNow );
System.out.println( "nowUtc: " + nowUtc );

When run.

input: Oct 04, 2015 2:11:58,757 AM UTC

then: 2015-10-04T02:11:58.757Z[UTC]

now: 2015-10-19T19:28:04.619-04:00[America/Montreal]

isThenBeforeNow: true

nowUtc: 2015-10-19T23:28:04.619Z


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

2 of 2
2

Upd2: Solved

Okay, now i get what i want:

DateFormat df = new SimpleDateFormat("MMM dd, yyyy K:mm:ss,SSS a z", Locale.ENGLISH);
Date date = df.parse("Oct 04, 2015 2:11:58,757 AM UTC");
long diff = TimeZone.getDefault().getRawOffset() - df.getTimeZone().getRawOffset();
date = new Date(date.getTime()-diff);

Anyway, thanks for everyone

🌐
Coderanch
coderanch.com › t › 385122 › java › Changing-timezone-date-display
Changing the timezone of a date, not only display (Java in General forum at Coderanch)
The only reason why you now see the date printed in UTC is because you are setting the default timezone of the JVM to UTC with this line: Note that now all Date objects will be printed with UTC, not just the Date object that is returned by the method. That's most likely not what you want! ... Ok. So, how do we solve this problem? I want to get the current date (java.util.Date) from this class and should be UTC.
🌐
Tabnine
tabnine.com › home page › code › java › java.util.date
java.util.Date java code examples | Tabnine
public boolean isDateExpired(String ... = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); df.setTimeZone(tz); // strip timezone return df.format(new Date()); }...
Find elsewhere
Top answer
1 of 16
137

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();
    }

}
2 of 16
55

The quick answer is :

No, you are not allowed to do that. Because that is what Date use for.

From javadoc of Date :

The class Date represents a specific instant in time, with millisecond precision.

However, since this class is simply a data object. It dose not care about how we describe it. When we see a date 2012/01/01 12:05:10.321, we can say it is 2012/01/01, this is what you need. There are many ways to do this.

Example 1 : by manipulating string

Input string : 2012/01/20 12:05:10.321

Desired output string : 2012/01/20

Since the yyyy/MM/dd are exactly what we need, we can simply manipulate the string to get the result.

String input = "2012/01/20 12:05:10.321";
String output = input.substring(0, 10);  // Output : 2012/01/20

Example 2 : by SimpleDateFormat

Input string : 2012/01/20 12:05:10.321

Desired output string : 01/20/2012

In this case we want a different format.

String input = "2012/01/20 12:05:10.321";
DateFormat inputFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = inputFormatter.parse(input);

DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
String output = outputFormatter.format(date); // Output : 01/20/2012

For usage of SimpleDateFormat, check SimpleDateFormat JavaDoc.

🌐
Stack Overflow
stackoverflow.com › questions › 14488111 › remove-timezone-format
java - Remove timezone format - Stack Overflow
The original date object has the correct date and time, but I need to use Calendar (for xs:dateTime), but the timezone always appears. ... This is determined by the technology you're using to serialize the java into XML, not anything to do with the java.util.Date or java.util.Calendar.
🌐
CodingTechRoom
codingtechroom.com › question › truncate-time-java-date
How to Truncate Time from a Java Date Object? - CodingTechRoom
Timezone differences can affect the output when truncating dates especially across regions. Use the Calendar class to set the time fields (hours, minutes, seconds, milliseconds) to zero. Alternatively, use the LocalDate class from Java 8 and beyond for a more straightforward date manipulation ...
🌐
Coderanch
coderanch.com › t › 574089 › java › convert-date-object-time-zone
convert date object in any time zone to GMT or remove time zone (Java in General forum at Coderanch)
If that doesn't meet your needs, ... You may also consider looking into Joda Time. It has features that Java's core date/time classes lack. ... Boost this thread! ... About timezones! ... Converting from GMT to Local Timezone using two seperate fields (date & time...
🌐
Mkyong
mkyong.com › home › java › java – convert date and time between timezone
Java - Convert date and time between timezone - Mkyong.com
August 22, 2016 - Article is updated with the new java.time – ZonedDateTime example. And this should be the preferable solution. ... I have an issue here. I have gone through all the related post but wasnt able to get rid of this situation. I am trying to convert a US/Pacific date from string to a date object: SimpleDateFormat df = new SimpleDateFormat(“dd-MM-yy HH:mm:SS a z”); df.setTimeZone(TimeZoneUtil.getTimeZone(“US/Pacific”)); String userTime = df.format(date);// User Time – Returns correct US/Pacific time Date userDate = df.parse(userTime); // Always returns the date in EDT
🌐
CodingTechRoom
codingtechroom.com › question › -efficiently-remove-time-java-date-object
How Can I Efficiently Remove Time from a Java Date Object? - CodingTechRoom
Solution: Always convert dates to UTC or the desired timezone before manipulation. ... Learn how to fix cyclic ManageBean detection errors in JSF with expert advice and practical solutions. ... Learn how to effectively use regular expressions in Java to replace placeholders with values from a HashMap including example code and troubleshooting tips.