how to retrieve day month and year from Timestamp(long format)

后端 未结 5 1019
再見小時候
再見小時候 2020-12-15 17:38

I need to retrieve day year and month from a timestamp object as long numbers:

public long getTimeStampDay()
    {

            String iDate = new SimpleDate         


        
相关标签:
5条回答
  • 2020-12-15 18:07

    Seeing that you are using a dateformat in each method, you can use a different format string in each. For example:

    public long getTimeStampDay()
        {
    
                String day = new SimpleDateFormat("dd")
            .format(new Date(born_date.getDate())); 
             .....
    
                  return Long.parseLong(day); //just the day
    
        }
    
    0 讨论(0)
  • 2020-12-15 18:17

    A little refreshment of this well-accepted thread that is a bit outdated by now.

    Back in the day, Java 8 introduced Date and Time API which makes extracting much cleaner.

    Let's assume that bornDate is instance of LocalDateTime.

    bornDate.getDayOfMonth(); // extracts day of month
    bornDate.getMonth();      // extracts month
    bornDate.getYear();       // extracts year
    

    Oracle reference: Java SE 8 Date and Time

    0 讨论(0)
  • 2020-12-15 18:24
    long timestamp = bornDate.getTime();
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(timestamp);
    return cal.get(Calendar.YEAR);
    

    There are calendar fields for each property you need.

    Alternatively you can use joda-time:

    DateTime dateTime = new DateTime(bornDate.getDate());
    return datetime.getYear();
    
    0 讨论(0)
  • 2020-12-15 18:24

    I found a simple way to do that:

    born_date.getDay();
    born_date.getMonth();
    born_date.getYear();
    

    even if method getDay getMonth and getYear are deprecated. I think that Bozho solution is the best one.

    0 讨论(0)
  • 2020-12-15 18:29

    This method returns the day, date, year and time:

    Timestamp timestamp = new Timestamp(System.currentTimeMillis());
    
    0 讨论(0)
提交回复
热议问题