Home > Java > J2ME Current date and Time

J2ME Current date and Time

This simple J2ME application shows you how to get the current date ant time in J2ME and do the formatting of what format you want it to. Like core Java, J2ME too use the same java.util package to show the current date as well as current time on the screen.

The middlet we create here will show the current date and time when we started it. Each time we press the start button, the it will display the current date and time the button pressed. Here is the look of the finished application:

image

Here is the source code of the middlet.

 

import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

/**
* @author daniel
*/
public class ShowDateTime extends MIDlet implements CommandListener {

    private Display disp;
    private Date d;
    Calendar c = Calendar.getInstance();
    String time;
    private DateField currentDate;
    private Command start, exit;
    private Form form;
    private int index;

    public ShowDateTime() {
        form = new Form("Data and Time");
        d = new Date();
        start = new Command("start", Command.SCREEN, 1);
        exit = new Command("Exit", Command.EXIT, 0);
        currentDate = new DateField("", DateField.DATE_TIME);
        currentDate.setDate(d);
    }

    public void startApp() {
        form.append("CURRENT TIME IS: ");
        index = form.append(currentDate);
        form.addCommand(start);
        form.addCommand(exit);
        form.setCommandListener(this);
        disp = Display.getDisplay(this);
        disp.setCurrent(form);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command cmd, Displayable s) {
        if (cmd == exit) {
            notifyDestroyed();
        } else if (cmd == start) {
            d = new Date();
            c.setTime(d);
            time =  c.get(Calendar.YEAR)
                    + "-" + c.get(Calendar.MONTH)
                    + "-" + c.get(Calendar.DATE)
                    + " " + c.get(Calendar.HOUR_OF_DAY)
                    + ":" + c.get(Calendar.MINUTE)
                    + ":" + c.get(Calendar.SECOND);
            form.append( time);
        }
    }
}

 

Akhmad Daniel Sembiring

vitraining.com – CEO

  • Share/Bookmark
Categories: Java Tags:
  1. No comments yet.
  1. No trackbacks yet.
This site uses a Hackadelic PlugIn, Hackadelic SEO Table Of Contents 1.6.0.