Search code examples
javacalendarsimpledateformatmonthcalendargettime

Generate month in character from calendar java into a variable


Good day all,

I was trying to create a date variable by using Calendar java, the following is my example code:

long day = System.currentTimeMillis();
Calendar cal = Calendar.getInstance();
java.text.SimpleDateFormat month = new java.text.SimpleDateFormat("MMM"); // not sure how to assign this value inside
cal.setTimeInMillis(day);
cal.set(Calendar.HOUR_OF_DAY, 00);
cal.set(Calendar.MINUTE, 00);
cal.set(Calendar.SECOND, 00);
cal.set(Calendar.MILLISECOND, 000);
Date todayDate = cal.getTime();

Timestamp current = new Timestamp(todayDate.getTime());

However, the value of current I get is 2014-01-13 00:00:00.0. I prefer to set the 01 to Jan instead.

Any ideas on this?


Solution

  • You mean something like so?

            long day = System.currentTimeMillis();
            Calendar cal = Calendar.getInstance();
            java.text.SimpleDateFormat month = new java.text.SimpleDateFormat("yyyy-MMM-dd HH:mm:ss:S"); // not sure how to assign this value inside
            cal.setTimeInMillis(day);
            cal.set(Calendar.HOUR_OF_DAY, 00);
            cal.set(Calendar.MINUTE, 00);
            cal.set(Calendar.SECOND, 00);
            cal.set(Calendar.MILLISECOND, 000);
            Date todayDate = cal.getTime();
    
            Timestamp current = new Timestamp(todayDate.getTime());
            System.out.println(month.format(current));
    

    Yields:

    2014-Jan-13 00:00:00:0

    Please check the SimpleDateFormat for more formatting options.