Update system time via Shell. - Java Native OS

Java examples for Native OS:Shell Command

Description

Update system time via Shell.

Demo Code


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main{
    /**//from w  w  w.ja  va  2 s . c  om
     * my logger for debug and error-output.
     */
    static final Logger LOG = Logger.getLogger(SystemUtils.class.getName());
    /**
     * Update system time.
     * @param date New System Date and Time
     */
    public static void updateSystemTime(final Date date) {
        Date oldDate = new Date(); // is saved only for LOG message output
        SimpleDateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
        String actDate = fmt.format(date);
        fmt.applyPattern("HH:mm:ss");
        String actTime = fmt.format(date);
        try {
            switch (SystemInformation.getInstance().os()) {
            case WINDOWS:
                Runtime rt = Runtime.getRuntime();
                rt.exec("cmd /C date " + actDate);
                rt.exec("cmd /C time " + actTime);
                break;
            case LINUX:
                // with root permits only
                fmt.applyPattern("MM/dd/yyyy HH:mm:ss");
                actDate = fmt.format(date);
                // String cmdDate = "date -u -s'" + actDate + "' +'%D %T'";
                // execCommand(cmdDate);
                break;
            default:
                break;
            }
            fmt.applyPattern("dd-MM-yyyy HH:mm:ss");
            SystemUtils.LOG.log(
                    Level.INFO,
                    "SystemUtils.updateSystemTime() System time was updated from "
                            + fmt.format(oldDate) + " to "
                            + fmt.format(date));
        } catch (IOException e) {
            // cannot run commands
            SystemUtils.LOG
                    .log(Level.SEVERE,
                            "SystemUtils.updateSystemTime() Exception while updating sys time.",
                            e);
        }
    }
}

Related Tutorials