从输入字符串中找出日期

时间:2014-11-20 18:35:16

标签: java

我试图从给定的输入字符串中找出具体日期,这可能类似于" 201411W3"。我知道这个字符串的周是第3周(W3),事件将在星期五,所以我想找到第3个星期五的日期。我做了这样的事情:

public static Date getLastFriday( int month, int year ) {
    Calendar cal = Calendar.getInstance();
    cal.set( year, month, 1 );
    cal.add( Calendar.DAY_OF_MONTH, - ( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 8 ) );
    return cal.getTime();
}

当我打电话给这个方法时:getLastFriday(2014年11月),我得到的价值" Fri Nov 21 13:16:57 2014 2014"我需要解析以找出日期。有没有办法从结果中得到日期?

谢谢!

3 个答案:

答案 0 :(得分:1)

如果我理解你,那么你可以使用下面的代码作为参考 -

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Test{

    public static void main (String[] args)
    {
        String str="201411W3";
        String[] strSplitted = str.split("W");

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, Integer.parseInt(strSplitted[0].substring(4,6))-1);
        calendar.set(Calendar.YEAR, Integer.parseInt(strSplitted[0].substring(0,4)));
        calendar.set(Calendar.DAY_OF_MONTH, 1);

        if(calendar.get(Calendar.DAY_OF_WEEK)==7)
        {
            calendar.set(Calendar.WEEK_OF_MONTH, Integer.parseInt(strSplitted[1])+1);
        }   
        else
        {
            calendar.set(Calendar.WEEK_OF_MONTH, Integer.parseInt(strSplitted[1]));
        }

        calendar.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
        String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());

        System.out.println(formattedDate);
    }
}

Output : 2014-11-21您可以将格式更改为您想要的任何格式。

答案 1 :(得分:0)

如果您只想获得没有秒数的月和日,可以调用.get(Calendar.MONTH).get(Calendar.DATE)并将它们传递到新日期对象的构造函数中并返回该对象。

更多信息:here

答案 2 :(得分:0)

使用this SimpleDateFormat

我没有测试以下代码,但它的工作方式如下:

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date myDate = sdf.parse("Fri Nov 21 13:16:57 EST 2014");