2

So i have String trDate="20120106"; and want to get Date trDate=2012-01-06 and am trying to use SimpleDateFormat for changing the pattern but first i get to parse the string and then generate date and then try to call format which gives me back string but i need date, any suggestions, here is the code i have:

String trDate="20120106";    
Date tradeDate = new SimpleDateFormat("yyyymmdd", Locale.ENGLISH).parse(trDate);
String krwtrDate = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH).format(tradeDate);
Date krwTradeDate = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH).parse(krwtrDate);

Here is similar question but it does not answer my question

I need converted string in Date format only because i need to pass it to another function that expects Date object only.

Would really appreciate if someone can give example of how to get date in yyyy-mm-dd format from string which is in yyyymmdd format?

Community
  • 1
  • 1
Rachel
  • 100,387
  • 116
  • 269
  • 365
  • A `Date` object doesn't have a format. You can use it to convert to a string in any format. – adarshr Apr 20 '12 at 14:17
  • @adarshr: can you give me an example of how to get `date` in `yyyy-mm-dd` format from `string` which is in `yyyymmdd` format – Rachel Apr 20 '12 at 14:18
  • You said the other function expects `Date` object. So, there is no need for you to worry about the way it gets passed. Just construct a date (by using `SimpleDateFormat.parse` the way you're doing already) and pass it. – adarshr Apr 20 '12 at 14:19
  • but other function expects in the format `yyyy-mm-dd` and that is where this question comes in picture. – Rachel Apr 20 '12 at 14:21
  • 1
    Can you show the signature of the other function? If it's something like `void doSomethingWithDate(Date someDate)`, trust me, it'll be alright. – adarshr Apr 20 '12 at 14:21
  • @adarshr: It is exactly as you suggest but then while displaying, i would have `Fri Jan 06 00:01:00 EST 2012` but I need to date in `2012-01-06` to `soap call` – Rachel Apr 20 '12 at 14:25
  • 1
    Then you need to do this *inside* that method. You have to convert the incoming `Date` object into a `String` and pass to the soap call. I assume you already know how to convert `Date` to `String`? – adarshr Apr 20 '12 at 14:27
  • `Date.toString(date)` is what i would do to get string out of date – Rachel Apr 20 '12 at 14:30
  • 1
    No. You do `String krwtrDate = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH).format(someDate);` there. – adarshr Apr 20 '12 at 14:30
  • @Rachel The reason that `Date.toString(date)` is a bad choice is because it uses the default formatting for the current locale and timezone of the operating system. This typically adds in hours, minutes, and seconds, the timezone code, does timezone shifting of the time. In short, this rarely puts the date in the format you really want. If you want a specific format, you are formatting it correctly in the code above, but if the API takes a `Date` object, you cannot pass it a `String`, so don't format it. Formatting and parsing is `Date` to `String` conversion, not `Date` configuration. – Edwin Buck Apr 20 '12 at 14:54

4 Answers4

7

--- Answer updated due to commentary ---

Ok, so the API you are using demands a String, which represents a Date in the format of 2012-04-20

You then need to parse the incorrectly formatted Date and then format it again in the needed format.

String trDate="20120106";    
Date tradeDate = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).parse(trDate);
String krwtrDate = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).format(tradeDate);

Also note that I changed your "month" designator, as you have made a very common mistake of using m for month. Due to the "hours:minutes:seconds" date formats have two common "names" that both start with m, minutes and months. Uppercase M is therefore used for months, while lowercase m is used for minutes. I'll bet that this is the real reason you're encountering problems.

--- Original post follows ---

If your APIneeds a java.util.Date, then you don't need to do as much as you have. You actually have the java.util.Date with just the two lines

String trDate="20120106";    
Date tradeDate = new SimpleDateFormat("yyyymmdd", Locale.ENGLISH).parse(trDate);

But this solution might not make sense without a quick review of what java.util.Dates are. Dates are things, but how they are presented is divorced from what they are.

At any moment in time, there is one Date instance that describes that moment in time. How that Date instance should be presented is not in agreement, it depends heavily on what language the viewer speaks, which country they are in, what rules the country has imposed (daylight savings time), and what their cultural background has done before.

As such, a Date has no single associated presentation. That's why every "get the X" method on Date is deprecated (where X is day, month, hour, year, etc.), with the exception of grabbing the milliseconds from the 0 date (known as the epoch).

So, for every Date that is to be properly presented, you need to convert it to a String using rules that are specific to the language, country, time zone, and cultural precedent. The object that understands these rules and applies them is the DateFormat.

Which means, once you get the Date you don't need to reformat it and re-parse it to get the "right" Date as the two dates should be the same (for the same locale).

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
  • I agree with you but the thing is `soap api` call expects date in `yyyy-mm-dd` format and I have string format in `yyyymmdd` format, so I want to first convert `yyyymmdd` to `yyyy-mm-dd` format in string and then convert this string to date object using `SimpleFormat` parse method but right now I do not see that as an viable option. – Rachel Apr 20 '12 at 14:34
  • @Rachel Just convert `yyyymmdd` to a `Date` and pass to your method. Don't do any conversions yet. Once you're inside the method, then convert the `Date` back to the `String` in the format you want, `yyyy-mm-dd` – adarshr Apr 20 '12 at 14:37
  • In that case, you don't need to pass in a `Date`, you need to pass in a `String`. I'll update the answer (as these comment boxes are not the best place to paste code). – Edwin Buck Apr 20 '12 at 14:38
  • @EdwinBuck: API does not demand `string` but it demands `date` object – Rachel Apr 20 '12 at 14:44
  • @Rachel The post has been updated, and since `Date`s represent a moment in time (to the nearest millisecond), m could mean minute or month. Ambiguous formats are not desirable, so Java's `DateFormat` defines `m` to mean minute, and `M` to mean month. I'll bet that's the reason you're not getting expected output (as your format reads "years-minutes-days") – Edwin Buck Apr 20 '12 at 14:45
  • @Rachel Then give it a Date object. Why do you keep trying to re-format it into a `String`? Date objects _have no default_ format. They have _no format at all_, which is the reason that after you format one, you have a `String` and not a `Date`. – Edwin Buck Apr 20 '12 at 14:48
  • Yes you are right but now it appears that soap accepts `yyyy-mm-dd` string format and then internally it converts to date format. – Rachel Apr 20 '12 at 15:00
  • @Rachel Then give it a `String`. What confuses most of us is that you seem to flip-flop on what the API requests. Whatever it requests is what you must provide. Whatever it does internally is _its own business_. Don't micro-manage an API you haven't developed, as it probably does internal things for reasons you have not _yet_ discovered. Yes, it sometimes pays to be curious; but, remember that APIs are designed to be _used at their interface_, which is the only safe way of using them. – Edwin Buck Apr 20 '12 at 15:40
  • @EdwinBuck: I agree Edwin, it's just that I am not sure how api is working internally and rightly that should not be my business. – Rachel Apr 20 '12 at 15:43
  • @Rachel It's still fun to look, just don't dig so deeply that you get confused as to what the interface requests. Give it what it wants at the front door, and if you want to stroll in and start peeking around, that's fine. Just remember that whatever you find inside, it's only guaranteed to work if you go back to its front door _and give it what it wants at the front door_. – Edwin Buck Apr 20 '12 at 15:51
  • +1 for your detailed explanation and advise, this chat has enlightened my knowledge – Rachel Apr 20 '12 at 16:27
0

can you give me an example of how to get date in yyyy-mm-dd format from string which is in yyyymmdd format

A Date objects does not have a format associated with it. Internally it typically just stores a long value.

If some other methods is responsible for printing the date, then you unfortunately have no control over how the resulting output is formatted.

aioobe
  • 413,195
  • 112
  • 811
  • 826
0

Do I understand it well?

You have a method which only accepts Date as parameter, and internally that method converts the Date to a string in the wrong format using toString()?

Best is to modify that method and exchange the use of toString() with SimpleDateFormat.format().

If you can't modify that method, than you can "cheat" with OO, i. e. replace the toString method with your own implementation, for example like this:

public class MyDate {
   private static final FMT = SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);

   MyDate(long time) {
      super(time);
   }

   String toString() {
      return FMT.format(this);
   }
}

and you call your method with

xxx = myMethod(new MyDate(new SimpleDateFormat("yyyymmdd", Locale.ENGLISH).parse(trDate).getTime()));

But if that method does not use toString internally but SimpleDateFormat with the wrong format, then my proposition does not work.

Johanna
  • 5,223
  • 1
  • 21
  • 38
-2

If the String date always comes in the format you have mentioned than you can use the subString method to extract the year, month and day.

String trDate="20120106";

Using the subString method for String extract the Year, month and day

String year = "2012";
String month = "01";
String day = "06";

And parse these to integer. Assuming you will do the parsing of string to integer

int intYear = 2012;
int intMonth = 01;
int intDay = 06;

Calendar calendar= new GregorianCalendar(intYear, intMonth - 1, intDay);

Date date = new Date(calendar);

Community
  • 1
  • 1
Kamal
  • 3,878
  • 4
  • 21
  • 24