Get day, month and year separately using SimpleDateFormat

ぐ巨炮叔叔 提交于 2019-12-21 01:19:12

问题


I have a SimleDateFormat like this

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".

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


回答1:


If you need to get the values separately, then use more than one 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.




回答2:


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



回答3:


Wow, SimpleDateFormat for getting string parts? It can be solved much easier if your input string is like "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 SimpleDateFormat because of some reason, the solution will be the following:

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



回答4:


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

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

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



回答5:


tl;dr

Use LocalDate class.

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

… or .getMonthValue() or .getDayOfMonth.

java.time

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

LocalDate

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

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

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.




回答6:


Use this to parse "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.




回答7:


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

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




回答8:


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


来源:https://stackoverflow.com/questions/22989840/get-day-month-and-year-separately-using-simpledateformat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!