没有dateFormat.applyPattern() 方法
时间: 2024-05-08 09:21:27 浏览: 27
如果你在使用 Java 中的 SimpleDateFormat 类时,发现它没有 applyPattern() 方法,那么可能是因为你使用的是 Android 平台上的 Java 库,而不是标准的 Java 库。在 Android 中,SimpleDateFormat 类重写了 applyPattern() 方法,并将其替换为了 setDateFormat() 方法。
因此,如果你想在 Android 中设置 SimpleDateFormat 的格式,可以使用以下代码:
```java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setDateFormat("yyyy-MM-dd");
```
注意,在标准的 Java 库中,applyPattern() 方法是可用的,因此,在使用标准的 Java 库时,你可以使用以下代码设置 SimpleDateFormat 的格式:
```java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.applyPattern("yyyy-MM-dd");
```
相关问题
出生年月脱敏工具类
您好,出生年月脱敏工具类可以使用 Java 的 SimpleDateFormat 类进行实现。您可以使用以下代码进行实现:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtils {
// 出生年月日脱敏为****
private static final String BIRTHDAY_MASK = "****";
/**
* 将出生年月日进行脱敏
*
* @param birthDate 出生年月日,格式为 yyyy-MM-dd
* @return 脱敏后的出生年月日,格式为 ****-**-**
*/
public static String maskBirthDate(String birthDate) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse(birthDate);
dateFormat.applyPattern("yyyy");
String year = dateFormat.format(date);
dateFormat.applyPattern("MM");
String month = dateFormat.format(date);
dateFormat.applyPattern("dd");
String day = dateFormat.format(date);
return BIRTHDAY_MASK + "-" + BIRTHDAY_MASK + "-" + BIRTHDAY_MASK.substring(0, 2) + day;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
```
在上述代码中,我们使用 SimpleDateFormat 类将出生日期转换为 Date 类型,并将其转换为需要的格式。其中,我们使用 BIRTHDAY_MASK 常量表示出生年月日脱敏后的格式,即年份和月份脱敏为 ****,日脱敏为 **。
java将yyyy-MM-dd HH:mm:ss 转为yyyy-MM-dd
可以使用Java中的SimpleDateFormat类来进行日期格式化。具体的代码如下:
```java
String dateString = "2022-11-11 11:11:11";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = dateFormat.parse(dateString);
dateFormat.applyPattern("yyyy-MM-dd");
String output = dateFormat.format(date);
System.out.println(output);
```
代码中首先定义了一个日期字符串dateString和一个SimpleDateFormat对象dateFormat,dateFormat的格式为"yyyy-MM-dd HH:mm:ss"。
然后使用dateFormat的parse方法将日期字符串解析为Date对象。
接着使用applyPattern方法将dateFormat的格式修改为"yyyy-MM-dd"。
最后使用dateFormat的format方法将Date对象格式化为字符串并输出。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)