如何将日期字符串解析为整数变量? [英] How to parse date string into integer variables?
问题描述
我有一个 String
,其格式如下:"dd-MM-yyyy"
.我试图将字符串的 dd
部分保存到整数 day
变量中.我想对 String
的 MM
和 yyyy
部分执行相同的操作.我可以想象每当"/" char
在中的当前索引处时,使用for循环解析
循环. String
来分隔 String
> for
I have a String
which is formatted like so: "dd-MM-yyyy"
. I am trying to get the dd
part of the string saved into a integer day
variable. I want to do the same for the MM
and yyyy
parts of the String
. I can imagine parsing the String
using a for loop to separate the String
whenever the "/" char
is at the current index in the for
loop.
如何将包含日期的 String
分别分为日,月和年,分成整数变量供我操作?也许由于成员方法或字段可以处理这个问题,所以将这个 String
转移到一个 Date
对象会更容易(只是一个想法).
How do I split the String
containing the date into day, month and year respectively, into integer variables for me to operate on? Perhaps transferring this String
to a Date
object would make it easier due to a member method or field that handles this (just a thought).
推荐答案
String date = "13-08-2016";
String[] values = date.split("-");
int day = Integer.parseInt(values[0]);
int month = Integer.parseInt(values[1]);
int year = Integer.parseInt(values[2]);
您可以使用 String.split(String regex)
方法将日期解析为 String
数组,然后将每个值转换为int.
You can use String.split(String regex)
method to parse the date to array of String
then convert each value to int.
JavaDoc:
public String [] split(String regex)将此字符串拆分为匹配项给定正则表达式的该方法的工作方式就像通过调用具有给定表达式和限制的两参数拆分方法零的参数.因此,结尾的空字符串不包含在其中结果数组.
public String[] split(String regex) Splits this string around matches of the given regular expression. This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
Read more here: String.split
这篇关于如何将日期字符串解析为整数变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!