我有一个名为date的LocalDate变量,当我打印它时显示1988-05-05,我需要将其转换为打印为05。1988年5月。如何做到这一点?
当前回答
在Joda库中有一个内置的方法来格式化LocalDate
import org.joda.time.LocalDate;
LocalDate localDate = LocalDate.now();
String dateFormat = "MM/dd/yyyy";
localDate.toString(dateFormat);
如果你还没有它-添加到build.gradle:
implementation 'joda-time:joda-time:2.9.5'
编码快乐!:)
其他回答
SimpleDateFormat将不能工作,如果他开始与LocalDate,这是新的在Java 8。在我看来,您必须使用DateTimeFormatter, http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html。
LocalDate localDate = LocalDate.now();//For reference
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd LLLL yyyy");
String formattedString = localDate.format(formatter);
应该是1988年5月5日。要获得日之后月之前的周期,可能必须使用“dd”。LLLL yyyy”
在Joda库中有一个内置的方法来格式化LocalDate
import org.joda.time.LocalDate;
LocalDate localDate = LocalDate.now();
String dateFormat = "MM/dd/yyyy";
localDate.toString(dateFormat);
如果你还没有它-添加到build.gradle:
implementation 'joda-time:joda-time:2.9.5'
编码快乐!:)
一个很好的方法是使用SimpleDateFormat,我会告诉你怎么做:
SimpleDateFormat sdf = new SimpleDateFormat("d MMMM YYYY");
Date d = new Date();
sdf.format(d);
我看到你有一个变量的日期:
sdf.format(variable_name);
欢呼。
可以简短为:
LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
在ProgrammersBlock帖子的帮助下,我想出了这个。我的需求略有不同。我需要获取一个字符串并将其作为LocalDate对象返回。我拿到的代码使用的是旧的Calendar和SimpleDateFormat。我想让它更与时俱进。这是我想到的。
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
void ExampleFormatDate() {
LocalDate formattedDate = null; //Declare LocalDate variable to receive the formatted date.
DateTimeFormatter dateTimeFormatter; //Declare date formatter
String rawDate = "2000-01-01"; //Test string that holds a date to format and parse.
dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
//formattedDate.parse(String string) wraps the String.format(String string, DateTimeFormatter format) method.
//First, the rawDate string is formatted according to DateTimeFormatter. Second, that formatted string is parsed into
//the LocalDate formattedDate object.
formattedDate = formattedDate.parse(String.format(rawDate, dateTimeFormatter));
}
希望这能帮助到一些人,如果有人看到了更好的方法来完成这个任务,请添加您的输入。
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap