Jeet
Jeet

Reputation: 781

How can I display time in AM/PM format

I wanted to display time in AM / PM format. Example : 9:00 AM I wanted to perform addition subtraction operation as well. My event will start from 9:00 AM all time. I wanted to add minutes to get the result schedule event. How can I do that other then making a custom Time class?

Start 9:00 AM Add 45 min, after addition Start Time 9:45 AM

Upvotes: 7

Views: 18162

Answers (10)

Anonymous
Anonymous

Reputation: 86223

java.time

I should like to contribute the modern answer

    // create a time of day of 09:00
    LocalTime start = LocalTime.of(9, 0);
    // add 45 minutes
    start = start.plusMinutes(45);

    // Display in 12 hour clock with AM or PM
    DateTimeFormatter timeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
            .withLocale(Locale.US);
    String displayTime = start.format(timeFormatter);
    System.out.println("Formatted time: " + displayTime);

The output is:

Formatted time: 9:45 AM

The SimpleDateFormat, Date and Calendar classes used in most of the other answers are not only poorly designed (the first in particular notoriously troublesome), they are also long outdated since java.time, the modern Java date and time API, was already out when this question was asked more than four years ago.

For a time to be displayed to a user I generally recommend the built-in formats that you get from DateTimeFormatter.ofLocalizedDate, .ofLocalizedTime and .ofLocalizedDateTime. Should you in some situation have particular formatting needs that are not met with the built-in formats, you may also specify your own, for example:

    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:mm a", Locale.US);

(This particular example is pointless since it gives the same result as above, but you may use it as a starting point and modify it to your needs.)

Link: Oracle tutorial: Date Time explaining how to use java.time.

Upvotes: 3

Kishore Reddy
Kishore Reddy

Reputation: 2454

   edit_event_time.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Calendar calendar =Calendar.getInstance();
            SimpleDateFormat sdf=new SimpleDateFormat("hh:mm a");
            String time = sdf.format(calendar.getTime());
            Log.e("time","time "+sdf.format(calendar.getTime()));
            String inputTime = time, inputHours, inputMinutes;

            inputHours = inputTime.substring(0, 2);
            inputMinutes = inputTime.substring(3, 5);

            TimePickerDialog mTimePicker = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {

                    if (selectedHour == 0) {
                        selectedHour += 12;
                        timeFormat = "AM";
                    } else if (selectedHour == 12) {
                        timeFormat = "PM";
                    } else if (selectedHour > 12) {
                        selectedHour -= 12;
                        timeFormat = "PM";
                    } else {
                        timeFormat = "AM";
                    }

                    String selectedTime = selectedHour + ":" + selectedMinute + " " + timeFormat;

                    edit_event_time.setText(selectedTime);

                }
            }, Integer.parseInt(inputHours), Integer.parseInt(inputMinutes), false);//mention true for 24 hour's time format
            mTimePicker.setTitle("Select Time");
            mTimePicker.show();
        }
    });

Upvotes: 0

JM Pascual
JM Pascual

Reputation: 1

Calendar cl = new GregorianCalendar();
int a = cl.get(Calendar.AM_PM);
if(a == 1) {
                        lbltimePeriod.setText("PM");
                    }
                    else
                    {
                        lbltimePeriod.setText("AM");
                    }

This would Definitely Solve your Problem, It Works for me 100%

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347184

Start with a SimpleDateFormat, this will allow you parse and format time values, for example...

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
try {
    // Get the start time..
    Date start = sdf.parse("09:00 AM");
    System.out.println(sdf.format(start));
} catch (ParseException ex) {
    ex.printStackTrace();
}

With this, you can then use Calendar with which you can manipulate the individual fields of a date value...

Calendar cal = Calendar.getInstance();
cal.setTime(start);
cal.add(Calendar.MINUTE, 45);
Date end = cal.getTime();

And putting it all together...

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
try {
    Date start = sdf.parse("09:00 AM");
    Calendar cal = Calendar.getInstance();
    cal.setTime(start);
    cal.add(Calendar.MINUTE, 45);
    Date end = cal.getTime();

    System.out.println(sdf.format(start) + " to " + sdf.format(end));
} catch (ParseException ex) {
    ex.printStackTrace();
}

Outputs 09:00 AM to 09:45 AM

Updated

Or you could use JodaTime...

DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendHourOfDay(2).appendLiteral(":").appendMinuteOfHour(2).appendLiteral(" ").appendHalfdayOfDayText().toFormatter();
LocalTime start = LocalTime.parse("09:00 am", dtf);
LocalTime end = start.plusMinutes(45);

System.out.println(start.toString("hh:mm a") + " to " + end.toString("hh:mm a"));

Or, if you're using Java 8's, the new Date/Time API...

DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendPattern("hh:mm a").toFormatter();
LocalTime start = LocalTime.of(9, 0);
LocalTime end = start.plusMinutes(45);

System.out.println(dtf.format(start) + " to " + dtf.format(end));

Upvotes: 16

Praveen Srinivasan
Praveen Srinivasan

Reputation: 1620

Easiest way to get it by using date pattern - h:mm a, where

h - Hour in am/pm (1-12)
m - Minute in hour
a - Am/pm marker
Code snippet :

DateFormat dateFormat = new SimpleDateFormat("hh:mm a");

Upvotes: 0

user3891540
user3891540

Reputation:

use the Simpledatetimeformat object to format time and calander object with date to add time date on the Date obeject

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

That is very easy with Calendar

    Calendar calendar =Calendar.getInstance();
    SimpleDateFormat sdf=new SimpleDateFormat("hh:mm a");
    sdf.format(calendar.getTime());
    System.out.println(sdf.format(calendar.getTime()));
    // i want to add 45mins now
    calendar.add(Calendar.MINUTE,45);
    System.out.println(sdf.format(calendar.getTime()));
    // i want to substract  30mins now
    calendar.add(Calendar.MINUTE,-30);
    System.out.println(sdf.format(calendar.getTime()));

Out put:

   10:49 AM
   11:34 AM
   11:04 AM

Upvotes: 0

Gaurav
Gaurav

Reputation: 19

There is a simple code to generate a time with AM/PH here is a code i give you please check this

import java.text.SimpleDateFormat; import java.util.Date;

public class AddAMPMToFormattedDate {

public static void main(String[] args) {

//create Date object
Date date = new Date();

 //formatting time to have AM/PM text using 'a' format
 String strDateFormat = "HH:mm:ss a";
 SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);

 System.out.println("Time with AM/PM field : " + sdf.format(date));

} }

Upvotes: -1

Scary Wombat
Scary Wombat

Reputation: 44824

as taken from http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

 "h:mm a"   gives 12:08 PM

to perform addition on time use The Calendar class

http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#add(int,%20int)

 Calendar rightNow = Calendar.getInstance();  // or use your own Date
 rightNow.add (Calendar.MINUTE, 45);

 DateFormat dateFormat = new SimpleDateFormat("hh:mm a");

 System.out.println(dateFormat.format (rightNow)); --> showing as am / pm

Upvotes: 0

Deepanshu J bedi
Deepanshu J bedi

Reputation: 1530

Find many examples like this here

import java.text.SimpleDateFormat;

import java.util.Date;

public class Main {

  public static void main(String[] args) {
    Date date = new Date();

    String strDateFormat = "HH:mm:ss a";
    SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
    System.out.println(sdf.format(date));
  }
}
//10:20:12 AM

DateFormat dateFormat = new SimpleDateFormat("hh:mm a");

Read this

Upvotes: 0

Related Questions