【问题标题】:Date object from simple string - Java and Android [duplicate]来自简单字符串的日期对象 - Java 和 Android [重复]
【发布时间】:2013-11-24 04:08:33
【问题描述】:

具体日期为“2013-11-12”。

我想从上述日期中提取日、月和年。请告诉我如何提取?

【问题讨论】:

标签: android simpledateformat


【解决方案1】:

您可以使用split()

示例:

String mydate="2013-11-12"; //year-month-day

String myyear=mydate.split("-")[0];  //0th index = 2013
String mymonth=mydate.split("-")[1]; //1st index = 11
String myday=mydate.split("-")[2];   //2nd index = 12

【讨论】:

    【解决方案2】:

    您可以使用 substring 方法从上面的字符串中提取特定字符,例如:

    String year=date.substring(0,4);   //this will return 2013
    String month=date.substring(5,7);  //this will return 11
    String day=date.substring(8,10);   //this will return 12
    

    【讨论】:

    • 如果是“2013-1-1”,你的就不可能是正确的
    • 它将被设置为默认值 2013-01-01 或者如果您知道日期将按此顺序排列,您可以将其更改为 String year=date.substring(0,4); //这将返回 2013 String month=date.substring(5,6); //这将返回 1 个字符串 day=date.substring(7,8); //这将返回 1
    【解决方案3】:

    你也可以使用Calendar

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2013-11-12"));
    int day = calendar.get(Calendar.DAY_OF_MONTH);
    int month = calendar.get(Calendar.MONTH);
    int year = calendar.get(Calendar.YEAR);
    

    【讨论】:

      【解决方案4】:

      您可以使用 SimpleDateFormatCalendar 类来实现。

      Calendar cal = Calendar.getInstance();
      SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
      cal.setTime(sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done
      

      现在你可以使用这个cal 对象做任何你想做的事情。不仅仅是日期、月份或年份。您可以使用它来执行各种操作,例如add monthadd year 等...

      【讨论】:

        【解决方案5】:

        首先从您的日期字符串创建日期对象,例如...

        String yourDateString = "2013-11-12";
        SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
        Date yourDate = parser.parse(yourDateString);
        

        现在创建日历实例以获取有关日期的更多信息...

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(yourDate);
        int months = calendar.get(Calendar.DAY_OF_MONTH); 
        int seconds = calendar.get(Calendar.SECOND); 
        // and similarly use calender.getXXX
        

        希望这会有所帮助...

        【讨论】:

        • @Bhavin: 赞赏...:)
        【解决方案6】:
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        
        Date testDate = null;
        
        try {
              testDate = sdf.parse("2013-11-12");
        }
        catch(Exception ex) {
              ex.printStackTrace();
        }
        
        int date= testDate.getDate();
        int month = testDate.getMonth();
        int year = testDate.getYear();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-17
          • 2011-10-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-22
          • 2011-12-19
          相关资源
          最近更新 更多