2

There are many questions like this on StackOverflow but no one has the answer I need. I have seen these 3 questions:

Get Value Of Day Month form Date Object in Android?
How to get month and day in android?
Get current time and date on Android

From these 3 questions I have learnt that to get date and time, we need to use Calendar. I have visited its documentation page but that is too hard to understand.

Now my question is I want to get current day i.e 12, current month i.e November, current year i.e 2014 and hour, minute, not seconds and AM or PM.

I only know till here:

Calendar c = Calendar.getInstance();

Now what should I do next?

Community
  • 1
  • 1
gegobyte
  • 4,945
  • 10
  • 46
  • 76
  • Possible duplicate of [How can I change date from 24-hours format to 12-hours format (am/pm) in android](http://stackoverflow.com/questions/9532463/how-can-i-change-date-from-24-hours-format-to-12-hours-format-am-pm-in-android) – Basil Bourque Mar 23 '16 at 02:59

6 Answers6

14

You can customize the format you want using

DateFormat df = new SimpleDateFormat("dd MM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());
Royce Raju Beena
  • 711
  • 4
  • 20
9
    Calendar calander = Calendar.getInstance(); 
    cDay = calander.get(Calendar.DAY_OF_MONTH);
    cMonth = calander.get(Calendar.MONTH) + 1;
    cYear = calander.get(Calendar.YEAR);
    selectedMonth = "" + cMonth;
    selectedYear = "" + cYear;
    cHour = calander.get(Calendar.HOUR);
    cMinute = calander.get(Calendar.MINUTE);
    cSecond = calander.get(Calendar.SECOND);
deepak825
  • 432
  • 2
  • 8
  • FYI, the troublesome date-time classes such as `java.util.Date`, `java.util.Calendar`, & `java.text.SimpleDateFormat` are now legacy, supplanted by the [*java.time*](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/package-summary.html) classes. Most *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android (<26) in [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP). See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Sep 27 '19 at 21:38
4

Use SimpleDateFormat to get date and time in desired format :

Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd,MMMM,YYYY hh,mm,a");
String strDate = sdf.format(c.getTime());
Haresh Chhelana
  • 24,720
  • 5
  • 57
  • 67
2
    Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
    Date currentTime = localCalendar.getTime();
    int currentDay = localCalendar.get(Calendar.DATE);
    int currentMonth = localCalendar.get(Calendar.MONTH) + 1;
    int currentYear = localCalendar.get(Calendar.YEAR);
    int currentDayOfWeek = localCalendar.get(Calendar.DAY_OF_WEEK);
    int currentDayOfMonth = localCalendar.get(Calendar.DAY_OF_MONTH);
    int CurrentDayOfYear = localCalendar.get(Calendar.DAY_OF_YEAR);

    System.out.println("Current Date and time details in local timezone");
    System.out.println("Current Date: " + currentTime);
    System.out.println("Current Day: " + currentDay);
    System.out.println("Current Month: " + currentMonth);
    System.out.println("Current Year: " + currentYear);
    System.out.println("Current Day of Week: " + currentDayOfWeek);
    System.out.println("Current Day of Month: " + currentDayOfMonth);
    System.out.println("Current Day of Year: " + CurrentDayOfYear);
Kuldeep Singh
  • 336
  • 3
  • 12
1

tl;dr

I want to get current day i.e 12, current month i.e November, current year i.e 2014 and hour, minute, not seconds and AM or PM.

ZonedDateTime
.now( 
    ZoneId.of( "Pacific/Auckland" )    // Or "Asia/India", "Africa/Tunis", etc.
)
.format(
    DateTimeFormatter
    .ofPattern(
        "dd MMMM uuuu HH:mm" 
    )
    .withLocale( 
        Locale.CANADA_FRENCH           // Or `Locale.US`, or `new Locale( "en" , "IN" )` for English language with India culture.
    )
)

See this code run live at IdeOne.com.

28 septembre 2019 08:48

java.time

From these 3 questions I have learnt that to get date and time, we need to use Calendar.

Nope.

The Calendar class is terrible, along with Date & SimpleDateFormat and such. These classes were all supplanted years ago by the modern java.time classes defined in JSR 310.

Now my question is I want to get current day i.e 12, current month i.e November, current year i.e 2014 and hour, minute, not seconds and AM or PM.

Determining a date and time-of-day requires a time zone. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If you want to depend on the JVM’s current default time zone, make your intention clear by calling ZoneId.systemDefault(). If critical, confirm the zone with your user.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;  

Capture the current moment as seen in the wall-clock time used by the people of a certain region (a time zone).

ZonedDateTime zdt = ZonedDateTime.now( z ) ;

If you do not care about the seconds or fractional-second, truncate.

ZonedDateTime zdt = ZonedDateTime.now( z ).truncatedTo( ChronoUnit.MINUTES ) ;

Generate a string in standard ISO 8601 format, wisely extended to append the name of the time zone in square brackets.

String output = zdt.toString() ;

2019-09-28T01:42+05:30[Asia/Kolkata]

Generate a string, automatically localized.

Locale locale = new Locale( "en" , "IN" ) ;  // English language, India culture.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.LONG ).withLocale( locale ) ;
String output2 = zdt.format( f ) ;

28 September 2019 at 1:42:00 AM IST

See this code run live at IdeOne.com.


Table of date-time types in Java, both modern and legacy


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.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

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?

Table of which java.time library to use with which version of Java or Android

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • you can use java.time in older API with Java 8+ API desugaring support (https://developer.android.com/studio/write/java8-support#library-desugaring) – Francis Jun 12 '20 at 15:03
0
public class XYZ extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.main);

    Calendar c = Calendar.getInstance();
    System.out.println("Current time => "+c.getTime());

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String formattedDate = df.format(c.getTime());
    // formattedDate have current date/time
    Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();


  // Now we display formattedDate value in TextView
    TextView txtView = new TextView(this);
    txtView.setText("Current Date and Time : "+formattedDate);
    txtView.setGravity(Gravity.CENTER);
    txtView.setTextSize(20);
    setContentView(txtView);
  }

 }


Calendar calander = Calendar.getInstance(); 
cDay = calander.get(Calendar.DAY_OF_MONTH);
cMonth = calander.get(Calendar.MONTH) + 1;
cYear = calander.get(Calendar.YEAR);
selectedMonth = "" + cMonth;
selectedYear = "" + cYear;
cHour = calander.get(Calendar.HOUR);
cMinute = calander.get(Calendar.MINUTE);
cSecond = calander.get(Calendar.SECOND);
Naveen Tamrakar
  • 3,349
  • 1
  • 19
  • 28
  • I want date and time in parts. Current day in int, name of month in String, year in int, hour and minute in int and AM or PM in String. – gegobyte Nov 12 '14 at 05:46
  • Change the arguments supplied to the SimpleDateFormat in my answer above and to get integers use Integer.parseInt(string) to convert those that you need as integers – Royce Raju Beena Nov 12 '14 at 06:43