English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Base Tutorial

Contrôle de flux Java

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Java Exception Handling

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

Java程序获取当前日期/时间

Java example complete set

在该程序中,您将学习以Java格式获取当前日期和时间。

示例1:以默认格式获取当前日期和时间

import java.time.LocalDateTime;
public class CurrentDateTime {}}
    public static void main(String[] args) {
        LocalDateTime current = LocalDateTime.now();
        System.out.println("当前日期和时间为: " + current);
    }
}

When running the program, the output is:

当前日期和时间为: 2019-08-02T11:25:44.973

在上面的程序中,使用LocalDateTime.now()方法将当前日期和时间存储在变量current中

对于默认格式,只需使用toString()方法在内部将其从LocalDateTime对象转换为字符串

示例2:使用模式获取当前日期和时间

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class CurrentDateTime {}}
    public static void main(String[] args) {
        LocalDateTime current = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy"-MM-dd HH:mm:ss.SSS);
        String formatted = current.format(formatter);
        System.out.println("当前日期和时间为: " + formatted);
    }
}

When running the program, the output is:

当前日期和时间为: 2017-08-02 11:29:57.401

在上面的程序中,我们使用DateTimeFormatter对象定义了格式为Year-Month-Day Hours:Minutes:Seconds.Milliseconds的模式

然后,我们使用LocalDateTime的format()方法来使用给定formatter。这使我们获得格式化的字符串输出。

示例3:使用预定义的常量获取当前日期时间

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class CurrentDateTime {}}
    public static void main(String[] args) {
        LocalDateTime current = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;
        String formatted = current.format(formatter);
        System.out.println("The current date is: "); + formatted);
    }
}

When running the program, the output is:

当前日期是: 20170802

在上面的程序中,我们使用了预定义的格式常量BASIC_ISO_DATE来获取当前ISO日期作为输出。

示例4:以本地化样式获取当前日期时间

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
public class CurrentDateTime {}}
    public static void main(String[] args) {
        LocalDateTime current = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
        String formatted = current.format(formatter);
        System.out.println("The current date is: "); + formatted);
    }
}

When running the program, the output is:

The current date is: Aug 2, 2017 11:44:19 AM

In the above program, we used the localized style Medium to obtain the current date and time in the given format. There are other styles as well: Full, Long, and Short.

Java example complete set