Java Basic Problems

Java: How to know it is AM or PM using Time / DateFormat in java.

If you are trying to separate the AM or PM from the Time or DateFormat using java, then the following solution will be helpful for you.

Code Example:

import java.text.*;

import java.util.*;

import java.util.StringTokenizer;

class DateFormatDemo {

public static void main(String args[]) {

Date date = new Date();

DateFormat df;

df = DateFormat.getDateInstance(DateFormat.SHORT);


System.out.println(“Short form: ” + df.format(date));

df = DateFormat.getDateInstance(DateFormat.LONG);

System.out.println(“Long form: ” + df.format(date));


df = DateFormat.getTimeInstance(DateFormat.SHORT);

System.out.println(“Short form: ” + df.format(date));

df = DateFormat.getTimeInstance(DateFormat.LONG);

System.out.println(“Long form: ” + df.format(date));

String daate=df.format(date).toString();


StringTokenizer st_time=new StringTokenizer(daate,” “);

                         String timeStr[] = new String[7];

                         int i=0;

                         while ( st_time.hasMoreElements()) {

                         timeStr[i++] = st_time.nextToken();   


System.out.println(“It is AM or PM ?:”+timeStr[1]);




AM or PM java

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s