Java 使用 SimpleDateFormat 分别获取日、月和年

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22989840/
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-13 19:48:53  来源:igfitidea点击:

Get day, month and year separately using SimpleDateFormat

javaandroiddatesimpledateformat

提问by John Error

I have a SimleDateFormatlike this

我有一个SimleDateFormat这样的

SimpleDateFormat format = new SimpleDateFormat("MMM dd,yyyy  hh:mm");
String date = format.format(Date.parse(payback.creationDate.date));

I'm giving date with the format like "Jan,23,2014".

我用类似的格式给出日期"Jan,23,2014"

Now, I want to get day, month and year separately. How can I implement this?

现在,我想分别获得日、月和年。我该如何实施?

采纳答案by Duncan Jones

If you need to get the values separately, then use more than one SimpleDateFormat.

如果您需要分别获取这些值,请使用多个SimpleDateFormat.

SimpleDateFormat dayFormat = new SimpleDateFormat("dd");
String day = dayFormat.format(Date.parse(payback.creationDate.date));

SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
String month = monthFormat .format(Date.parse(payback.creationDate.date));

etc.

等等。

回答by Mani

Are you accepting this ?

你接受这个吗?

int day = 25 ; //25
int month =12; //12
int year = 1988; // 1988
Calendar c = Calendar.getInstance();
c.set(year, month-1, day, 0, 0);    
SimpleDateFormat format =   new SimpleDateFormat("MMM dd,yyyy  hh:mm");
System.out.println(format.format(c.getTime()));

Display as Dec 25,1988 12:00

显示为 Dec 25,1988 12:00

UPDATE : based on Comment

更新:基于评论

DateFormat format =   new SimpleDateFormat("MMM");
System.out.println(format.format(format.parse("Jan,23,2014")));

NOTE: Date.parse() is @deprecated and as per API it is recommend to use DateFormat.parse

注意:Date.parse() 是@deprecated,根据 API 建议使用 DateFormat.parse

回答by John Ding

Use this to parse "Jan,23,2014"

使用它来解析“Jan,23,2014”

SimpleDateFormat fmt = new SimpleDateFormat("MMM','dd','yyyy"); 
Date dt = fmt.parse("Jan,23,2014");

then you can get whatever part of the date.

那么你可以得到日期的任何部分。

回答by nikis

Wow, SimpleDateFormatfor getting string parts? It can be solved much easier if your input string is like "Jan,23,2014":

哇,SimpleDateFormat为了获得弦乐零件?如果您的输入字符串类似于“Jan,23,2014”,则可以更轻松地解决该问题:

String input = "Jan,23,2014";
String[] out = input.split(",");
System.out.println("Year = " + out[2]);
System.out.println("Month = " + out[0]);
System.out.println("Day = " + out[1]);

Output:

输出:

Year = 2014
Month = Jan
Day = 23

But if you really want to use SimpleDateFormatbecause of some reason, the solution will be the following:

但是如果SimpleDateFormat因为某种原因真的要使用的话,解决办法如下:

String input = "Jan,23,2014";
SimpleDateFormat format = new SimpleDateFormat("MMM,dd,yyyy");
Date date = format.parse(input);
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
calendar.setTime(date);
System.out.println(calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
System.out.println(new SimpleDateFormat("MMM").format(calendar.getTime()));

Output:

输出:

2014
23
Jan

回答by Udo Klimaschewski

    SimpleDateFormat format = new SimpleDateFormat("MMM dd,yyyy  hh:mm", Locale.ENGLISH);

    Date theDate = format.parse("JAN 13,2014  09:15");

    Calendar myCal = new GregorianCalendar();
    myCal.setTime(theDate);

    System.out.println("Day: " + myCal.get(Calendar.DAY_OF_MONTH));
    System.out.println("Month: " + myCal.get(Calendar.MONTH) + 1);
    System.out.println("Year: " + myCal.get(Calendar.YEAR));

回答by Thanh Thinh

public static String getDate(long milliSeconds, String dateFormat) {
        // Create a DateFormatter object for displaying date in specified
        // format.
        SimpleDateFormat formatter = new SimpleDateFormat(dateFormat,
                Locale.getDefault());

        // Create a calendar object that will convert the date and time value in
        // milliseconds to date.
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliSeconds);
        return formatter.format(calendar.getTime());
    }

回答by Thanh Thinh

The accepted answer here suggests to use more than one SimpleDateFormat, but it's possible to do this using one SimpleDateFormatinstance and calling applyPattern.

此处接受的答案建议使用多个SimpleDateFormat,但可以使用一个SimpleDateFormat实例并调用applyPattern.

Note: I believe this post would also be helpful for those who were searching for setPattern() just like me.

注意:我相信这篇文章对那些和我一样正在搜索 setPattern() 的人也会有所帮助。

Date date=new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
simpleDateFormat.applyPattern("dd");
System.out.println("Day   : " + simpleDateFormat.format(date));
simpleDateFormat.applyPattern("MMM");
System.out.println("Month : " + simpleDateFormat.format(date));
simpleDateFormat.applyPattern("yyyy");
System.out.println("Year  : " + simpleDateFormat.format(date));

回答by Basil Bourque

tl;dr

tl;博士

Use LocalDateclass.

使用LocalDate类。

LocalDate
.parse(
    "Jan,23,2014" , 
    DateTimeFormatter.ofPattern( "MMM,dd,uuuu" , Locale.US )
)
.getYear()

… or .getMonthValue()or .getDayOfMonth.

... 或.getMonthValue().getDayOfMonth

java.time

时间

The other Answers use outmoded classes. The java.time classes supplant those troublesome old legacy classes.

其他答案使用过时的类。java.time 类取代了那些麻烦的旧遗留类。

LocalDate

LocalDate

The LocalDateclass represents a date-only value without time-of-day and without time zone.

LocalDate级表示没有时间一天和不同时区的日期,唯一的价值。

String input = "Jan,23,2014";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM,d,uuuu" );
LocalDate ld = LocalDate.parse( input , f );

Interrogate for the parts you want.

询问您想要的部分。

int year = ld.getYear();
int month = ld.getMonthValue();
int dayOfMonth = ld.getDayOfMonth();


About java.time

关于java.time

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

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

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

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

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

您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject 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.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多