Java 从 Date 对象中删除时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9816459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 08:02:56  来源:igfitidea点击:

Removing time from a Date object?

javadatetimedate

提问by Laxman Rana

I want to remove time from Dateobject.

我想从Date对象中删除时间。

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 Stringformat) it is appending time also.

但是当我转换这个日期(String格式)时,它也在附加时间。

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

我根本不想要时间。我想要的只是“21/03/2012”。

采纳答案by Rangi Lin

The quick answer is :

快速答案是:

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

不,你不能这样做。因为那是Date用来做什么的。

From javadoc of Date:

来自 javadoc 的Date

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

类 Date 表示特定的时刻,精度为毫秒。

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.

然而,由于这个类只是一个数据对象。它不在乎我们如何描述它。当我们看到一个日期时2012/01/01 12:05:10.321,我们可以说它是2012/01/01,这就是您所需要的。有很多方法可以做到这一点。

Example 1 : by manipulating string

示例 1:通过操作字符串

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

输入字符串:2012/01/20 12:05:10.321

Desired output string : 2012/01/20

所需的输出字符串:2012/01/20

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

由于 yyyy/MM/dd 正是我们所需要的,我们可以简单地操作字符串来获得结果。

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

Example 2 : by SimpleDateFormat

示例 2:通过 SimpleDateFormat

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

输入字符串:2012/01/20 12:05:10.321

Desired output string : 01/20/2012

所需的输出字符串: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.

对于 的用法SimpleDateFormat,请检查SimpleDateFormat JavaDoc

回答by Jeremy Sayers

String substring(int startIndex, int endIndex)

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

换句话说,你知道你的字符串将是 10 个字符长,所以你会这样做:

FinalDate = date.substring(0,9);

回答by ?eurobur?

java.util.Date represents a date/timedown 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).

java.util.Date 表示精确到毫秒的日期/时间。你别无选择,只能包括一个时间。您可以尝试将时间归零,但随后时区和夏令时将发挥作用——这可能会把事情搞砸(e.g. 21/03/2012 0:00 GMT is 20/03/2012 PDT).

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

您可能想要的是 ajava.sql.Date仅表示日期部分(尽管在内部它仍然使用 ms)。

回答by Jesper

What you want is impossible.

你想要的是不可能的

A Dateobject represents an "absolute" moment in time. You cannot "remove the time part" from it. When you print a Dateobject 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.

一个Date对象代表一个“绝对”的时刻。您不能从中“删除时间部分”。当您Date直接使用打印对象时System.out.println(date),它将始终以包含时间的默认格式进行格式化。你无法改变这一点。

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

Date您应该寻找另一种解决方案,而不是以某种方式尝试将类用于它不是为它设计的东西。例如,使用SimpleDateFormat您想要的任何格式来格式化日期。

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-Timewhich has a much better and more powerful API.

遗憾的是,Java 日期和日历 API 并不是标准 Java API 中设计最完善的类。有一个名为Joda-Time的库,它有一个更好、更强大的 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 LocalDateclass would be what you'd use.

Joda-Time 有许多特殊的类来支持日期、时间、周期、持续时间等。如果你只想处理一个没有时间的日期,那么LocalDate你会使用Joda-Time 的类。

回答by Daniel

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

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

这已被弃用,但这是最快的方法。

回答by Sunil Manheri

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

您可以通过将小时、分钟、秒和毫秒值设置为零来从 java.util.Date 中删除时间部分。

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

}

回答by heretolearn

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

这会给你输出21/03/2012

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

或者,如果您希望输出为 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);
    }
}

回答by RNJ

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

有点虚伪,但您可以使用 java.sql.Date。这仅存储日期部分和基于零的时间(午夜)

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.

或者可能值得创建自己的日期对象,它只包含日期而不是时间。这可以包装 java.util.Date 并忽略它的时间部分。

回答by jseals

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

Apache Commons DateUtils有一个“截断”方法,我只是用来这样做的,我认为它会满足您的需求。它真的很容易使用:

DateUtils.truncate(dateYouWantToTruncate, Calendar.DAY_OF_MONTH);

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

DateUtils还具有许多其他很酷的实用程序,例如“isSameDay()”等。检查它!它可能会让你的事情变得更容易。

回答by Rajesh

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

您还可以根据您的要求手动更改“dd/mm/yyyy”模式中日期和格式的时间部分。

  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.

如果返回值不起作用,则检查 web.xml 中的上下文参数。例如。

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