user1318369
user1318369

Reputation: 715

find out the date from an input string

I am trying to find out the specific date from a given input string, which can be like "201411W3". I know that the week is 3rd from this string(W3) and the event will be on Friday, so I want to find the date of the 3rd Friday. I did something like this:

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();
}

when I call this method: getLastFriday(11, 2014), I get the value "Fri Nov 21 13:16:57 EST 2014" which I need to parse to find out the date. is there any way to get just the date from the result?

Thanks!

Upvotes: 0

Views: 61

Answers (3)

Kartic
Kartic

Reputation: 2985

If I understood you, then you can use below code as reference -

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 You can change the format to any format you want.

Upvotes: 1

L. Monty
L. Monty

Reputation: 882

Use this SimpleDateFormat

I didn't test the following code but it will work like:

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

Upvotes: 0

Seephor
Seephor

Reputation: 1732

If you just want to get the month and day without the seconds, you could call .get(Calendar.MONTH) and .get(Calendar.DATE) and pass them into the constructor of a new date object and return that object.

More info: here

Upvotes: 0

Related Questions