7

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

Jeet
  • 761
  • 3
  • 10
  • 27
  • possible duplicate of [Java string to date conversion](http://stackoverflow.com/questions/4216745/java-string-to-date-conversion) and [this](http://stackoverflow.com/q/13051298/642706) and [this](http://stackoverflow.com/q/15459001/642706) – Basil Bourque Jul 31 '14 at 06:17

10 Answers10

16

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));
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
3

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

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
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

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

Deepanshu J bedi
  • 1,530
  • 1
  • 11
  • 23
0

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
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
0

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

0

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");

Praveen Srinivasan
  • 1,562
  • 4
  • 25
  • 52
0
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%

  • Question was asked over three years ago and already has an accepted answer. Also your solution does not answer the question. OP was asking for time display in AM/PM format. Your solution just returns AM or PM. – Hintham Oct 10 '17 at 08:51
0
   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();
        }
    });
Kishore Reddy
  • 2,394
  • 1
  • 19
  • 15
-1

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));

} }

Gaurav
  • 19
  • 2