0

I have 2 strings: "Sun Jun 23" and "22:45". I want to get the long (millisecond?) representation of the date that is indicated by this 2 strings plus the actual year.

I am trying something like this:

String s1 = "Sun Jun 23";
String s2 = "22:45";
long date = new SimpleDateFormat("EEE MMM dd").parse(s1).getTime() 
          + new SimpleDateFormat("HH:mm").parse(s2).getTime();

When I convert back the long date format to String with

private SimpleDateFormat sdf;
sdf = new SimpleDateFormat("yyyy.MM.dd_HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
console.getOut().println(sdf.format(date));

I got "1970.06.23_20:45:00"

This indicates 2 problems:

  • This doesn't contain the current year. How can I add it?
  • Why did I 'lost' 2 hours (from 22:45 to 20:45)
user2448122
  • 195
  • 12

2 Answers2

2

Try concat the string then parse the date and get the time

String completeTime = s1 + " " + s2;
SimpleDateFormat sdf = new SimpleDateFormat ("EEE MMM dd HH:mm")
Date date = sdf.parse(completeTime)
long millis = date.getTime()

Edit.. Completely did read the whole question before sorry...

The year is not read in anywhere by your date so you will either have to add it or read it in from somewhere, if it is the year, I suggest using a Calendar object to get it

The Timezone information in the parse from your millis long seems to causing the time difference, you could try using "GMT+2" to correct this but this may not always be correct. If you take out the settin gof the timezone does it change your result?

Java Devil
  • 10,629
  • 7
  • 33
  • 48
  • Thanks for the tip. I am now using Calendar to get the current year, and concatenate all 3 strings. However I still have an issue (see my answer). – user2448122 Jun 23 '13 at 21:59
0

I got a bit further, but got a different issue:

String s1 = "Sun Jun 23";
String s2 = "22:45";
SimpleDateFormat f = new SimpleDateFormat("YYYY EEE MMM dd HH:mm");
f.setTimeZone(TimeZone.getTimeZone("GMT")); //thanks for the timezone hints!
Date d;
long date;
int year;
try {
    year = Calendar.getInstance().get(Calendar.YEAR);
    String fullDate = year + " " + s1 + " " + s2;
    d = f.parse(fullDate);
    date = d.getTime();
    SimpleDateFormat sdf2;
    sdf2 = new SimpleDateFormat("yyyy.MM.dd_HH:mm:ss");
    sdf2.setTimeZone(TimeZone.getTimeZone("GMT"));
    console.getOut().println(sdf2.format(date));
} catch (ParseException e) {
    e.printStackTrace();
} 

This prints out: 2012.12.30_22:45:00.

Timezone now looks okay (as I see 22:45),

fullDate contains the proper string ("2013 Sun Jun 23 22:45").

Why do I not get the correct date?

user2448122
  • 195
  • 12
  • 1
    Use lower case y's in your SimpleDateFormat f – Java Devil Jun 23 '13 at 22:06
  • 'Y' is Week Year, where as 'y' is Year, See [this](http://stackoverflow.com/questions/8686331/y-returns-2012-while-y-returns-2011-in-simpledateformat) post for more info. – Java Devil Jun 23 '13 at 23:26