java 正确的获取当前时间
时间: 2023-10-17 10:11:54 浏览: 51
获取当前时间可以使用Java中的Date类和DateFormat类。具体实现如下:
```
import java.util.*;
import java.text.*;
public class Main {
public static void main(String args[]) {
// 创建Date对象,表示当前时间
Date date = new Date();
// 创建DateFormat对象,定义日期格式
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 使用DateFormat对象格式化日期
String currentTime = dateFormat.format(date);
// 输出当前时间
System.out.println("当前时间:" + currentTime);
}
}
```
以上代码会输出当前时间的年、月、日、小时、分钟和秒数。如果需要精确到毫秒,只需要修改日期格式为"yyyy-MM-dd HH:mm:ss.SSS"。
相关问题
java获取当前时间是星期几
可以使用Java中的Calendar类来获取当前时间是星期几,具体实现代码如下:
```java
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
String[] weekDays = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
System.out.println("Today is " + weekDays[dayOfWeek - 1]);
}
}
```
运行以上代码,可以输出当前时间是星期几。注意,Calendar类中星期天是1,星期一是2,以此类推,因此需要对获取到的dayOfWeek进行-1操作才能得到正确的星期几。
java怎么获取当前目录
在 Java 中,可以使用 `System.getProperty("user.dir")` 方法来获取当前工作目录的路径。该方法返回一个字符串,表示当前工作目录的路径。
以下是一个示例代码:
```java
public class CurrentDirectoryExample {
public static void main(String[] args) {
// 获取当前工作目录的路径
String currentDirectory = System.getProperty("user.dir");
System.out.println("当前工作目录的路径:" + currentDirectory);
}
}
```
在上述代码中,我们使用 `System.getProperty("user.dir")` 方法获取当前工作目录的路径,并将其输出到控制台。
需要注意的是,当前工作目录是程序运行时的默认路径,它可能是一个相对路径或绝对路径,具体取决于程序的运行方式。在使用时应注意路径的正确性。