java - 简单日期格式设置为 01

标签 java simpledateformat

如何在 SimpleDateFormat 中将 01 放入日期,而不是今天的确切日期 当我使用

SimpleDateFormat day= new SimpleDateFormat("dd");

它给了我今天的确切日期..那么我该如何输入我的具体日期

SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
        String NOW = (sdf.format(new java.util.Date()));
        SimpleDateFormat month = new SimpleDateFormat("MM");
        String MONTH = (month.format(new java.util.Date()));
        SimpleDateFormat year = new SimpleDateFormat("yyyy");
        String YEAR = (year.format(new java.util.Date()));
        String PAST = ((MONTH)+"-"+(1)+"-"+(YEAR));

((MONTH)+"-"+(1)+"-"+(YEAR)); 返回 1 但它应该是 01 但当我运行它时,它只变成 1

最佳答案

tl;博士

YearMonth
.now(
    ZoneId.of( "America/Montreal" ) 
)
.atDay( 1 )
.format(
    DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
)

java.time

现代方法使用java.time类。切勿使用可怕的遗留类,例如 CalendarSimpleDateFormat

获取当前年份和月份。

YearMonth ym = YearMonth.now() ;

获取该月的第一天。

LocalDate ld = ym.atDay( 1 ) ;

指定您想要的格式模式。

DateTimeFormatter f =  DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) ;
String output = ld.format( f ) ;

关于java - 简单日期格式设置为 01,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52546698/

相关文章:

Java Date 对象解析精度在 SimpleDateFormat 上关闭

Java - 类层次结构

javascript - 在ZK中处理MouseScroll

java - 如何格式化我从 Dropbox 元数据调用到自定义表单中获得的时间戳?

java android DateFormat 忽略修改后的语言环境设置

java - 日期格式化时无法获得所需的输出

Java 在一行 if else 循环后设置值

java - 获取泛型类型参数的正确方法

java.lang.SecurityException : signer information does not match signer information of other classes in the same package in PowerMock

java - 在 Java 中将时间戳转换为简单日期并添加到 ParseObject