How can I get Date in MM/DD/YY format from Timestamp

后端 未结 7 1163
暗喜
暗喜 2020-12-16 11:27

I want to get the Date in MM/DD/YY format from a timestamp.

I have used the below method but it does not gives proper output

final Calen         


        
相关标签:
7条回答
  • 2020-12-16 11:53
    TimeZone utc = TimeZone.getTimeZone("UTC"); // avoiding local time zone overhead
    final Calendar cal = new GregorianCalendar(utc);
    
    // always use GregorianCalendar explicitly if you don't want be suprised with
    // Japanese Imperial Calendar or something
    
    cal.setTimeInMillis(1306249409L*1000); // input need to be in miliseconds
    
    Log.d("Date--",""+cal.get(Calendar.DAY_OF_MONTH));
    
    Log.d("Month--",""+cal.get(Calendar.MONTH) + 1); // it starts from zero, add 1
    
    Log.d("Year--",""+cal.get(Calendar.YEAR));
    
    0 讨论(0)
  • 2020-12-16 12:04
            Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
        String s = formatter.format(date);
        System.out.println(s);
    
    0 讨论(0)
  • 2020-12-16 12:05

    Better Approach

    Simply Use SimpleDateFormat

    new SimpleDateFormat("MM/dd/yyyy").format(new Date(timeStampMillisInLong));
    

    Mistake in your Approach

    DAY_OF_MONTH ,MONTH, .. etc are just constant int value used by Calendar class internally

    You can get the date represented by cal by cal.get(Calendar.DATE)

    0 讨论(0)
  • 2020-12-16 12:08

    What's wrong:

    Calendar.DAY_OF_MONTH, Calendar.MONTH etc are static constants used to access those particular fields. (They will remain constant, no matter what setTimeInMillis you provide.)


    How to solve it:

    To get those particular fields you can use the .get(int field)-method, like this:

    Log.d("Month--",""+cal.get(Calendar.MONTH));
    

    As others have pointed out there are more convenient methods for formatting a date for logging. You could use for instance the SimpleDateFormat, or, as I usually do when logging, a format-string and String.format(formatStr, Calendar.getInstance()).

    0 讨论(0)
  • 2020-12-16 12:09

    Use the SimpleDateFormat

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = new Date();
    String time = sdf.format(date);
    
    0 讨论(0)
  • 2020-12-16 12:13

    Java uses the number of milliseconds since 1st January 1970 to represent times. If you compute the time represented by 1306249409 milliseconds, you'll discover that it's only 362 days, so your assumptions are wrong.

    Moreover, cal.DAY_OF_MONTH holds a constant. Use cal.get(Calendar.DAY_OF_MONTH) to get the day of month (same for other parts of the date).

    0 讨论(0)
提交回复
热议问题