Thursday 19 July 2018

Get year, date, day, time from Calendar

'java.util.Calendar' class provides 'get' method, it returns the value of give calendar field (field can be year, month, day, hour, minute etc.,).

Example
Calendar.getInstance().get(Calendar.YEAR) : Return current year
Calendar.getInstance().get(Calendar.HOUR) : Return current hour



Find the below working example.

Test.java
package com.sample.app;

import static java.util.Calendar.DATE;
import static java.util.Calendar.HOUR;
import static java.util.Calendar.MILLISECOND;
import static java.util.Calendar.MINUTE;
import static java.util.Calendar.MONTH;
import static java.util.Calendar.SECOND;
import static java.util.Calendar.YEAR;

import java.text.DateFormatSymbols;
import java.util.Calendar;

public class Test {

 private static String getMonthFromInt(int num) {

  if (num < 0 || num > 11) {
   throw new IllegalArgumentException("Months should be in range of 0 to 11");
  }
  DateFormatSymbols dfs = new DateFormatSymbols();
  String[] months = dfs.getMonths();
  return months[num];
 }

 private static String getCurrentDate() {
  StringBuilder builder = new StringBuilder();
  Calendar cal = Calendar.getInstance();

  builder.append(cal.get(YEAR)).append("-").append(getMonthFromInt(cal.get(MONTH))).append("-")
    .append(cal.get(DATE)).append(" ").append(cal.get(HOUR)).append(":").append(cal.get(MINUTE)).append(":")
    .append(cal.get(SECOND)).append(":").append(cal.get(MILLISECOND));

  return builder.toString();
 }

 public static void main(String args[]) {

  System.out.println(getCurrentDate());
 }
}

Output
2018-July-19 6:49:17:383

You may like

Previous                                                    Next                                                    Home

No comments:

Post a Comment