-2

Let's say I have a String "January 2015". Now, what will be the correct way to convert it to a date and use it for comparison to other date?

anik_s
  • 243
  • 3
  • 18

2 Answers2

1

You can try like this;

public static void main(String[] args) throws ParseException {
    String stringDate = "January 2015";
    DateFormat df = new SimpleDateFormat("MMMM yyyy", Locale.ENGLISH);
    Date date = df.parse(stringDate);
    System.out.println(date); 
}

And the result is;

Thu Jan 01 00:00:00 VET 2015
Semih Eker
  • 2,389
  • 1
  • 20
  • 29
0

You can try this:

import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Locale;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String date = "January, 2015";
        SimpleDateFormat sdf = new SimpleDateFormat("MMMM, yyyy", Locale.ENGLISH);
        Date d = sdf.parse(date);
        System.out.println(date.toString());
    }
}

Output:

January, 2015

Working Example:

http://ideone.com/jmcSLO

Zelldon
  • 5,396
  • 3
  • 34
  • 46
  • Well, printing the `date` variable which just holds the source String is no proper proof for me :P. – Tom Apr 24 '15 at 08:44