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(“\n”);

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

df = DateFormat.getDateInstance(DateFormat.LONG);

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

System.out.println();

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

System.out.println(“\n”);

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

}

}

OUTPUT:

AM or PM java