我在String上有一个日期,如下所示:
String date="25.07.2007";
我想把它分成:
String day;
String month;
String year;
Run Code Online (Sandbox Code Playgroud)
做这个的最好方式是什么?
Tur*_*tle 11
在Java中拆分字符串的一种方法是使用.split("regex"),它根据提供的模式拆分字符串,返回一个String数组.
String [] dateParts = date.split(".");
String day = dateParts[0];
String month = dateParts[1];
String year = dateParts[2];
Run Code Online (Sandbox Code Playgroud)
获取当前日期:您还可以通过更改传递给SimpleDateFormat的值来更改日期的格式.不要忘记进口.
DateFormat dateFormater = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
Date date = new Date();
Run Code Online (Sandbox Code Playgroud)
现代方法是使用Java 8 及更高版本中内置的java.time框架的后向端口的Android 版本。
首先,将输入字符串解析为日期时间对象。该LocalDate级表示没有时间一天和不同时区的日期,唯一的价值。
String input = "25.07.2007";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MM.dd.yyyy" );
LocalDate localDate = LocalDate.parse( input , formatter );
Run Code Online (Sandbox Code Playgroud)
现在你可以询问LocalDate它的值。
int year = localDate.getYear();
int month = localDate.getMonthValue();
int dayOfMonth = localDate.getDayOfMonth();
Run Code Online (Sandbox Code Playgroud)
您可以使用方便的Month枚举来本地化月份的名称。
String monthName = localDate.getMonth().getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25156 次 |
| 最近记录: |