如何将日期字符串解析为整数变量? [英] How to parse date string into integer variables?

查看:65
本文介绍了如何将日期字符串解析为整数变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆