-2

I want my program to concat String variables (Date->int->String) but with a minus (-) sign between the Strings that I want to merge. For example: StringA + "-" + StringB or StringA.concat("-").concat(StringB). But if String a="100" and StringB="200" the operation would return me "-100" instead of "200-100". Why is this? Does String somehow converts Strings to int and then executes mathematical operations? No sense.

Code:

DateTime dt = new DateTime();
int sYear = dt.getYear();
int sMonth = dt.getMonthOfYear();
String minDate = null;
String y = Integer.toString(sYear);
String m = Integer.toString(sMonth);
minDate = y + "-" + m + "-01"; //or y.concat("-").concat(m).concat("-01");

The example I have above returns 1715.

Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135
Dainius Java
  • 125
  • 1
  • 4
  • 14
  • 2
    This is probably what you want... http://stackoverflow.com/questions/4216745/java-string-to-date-conversion – Tunaki Apr 22 '16 at 08:26
  • 1
    Hint: you never ever want to format dates manually. As you are re-inventing the wheel, and worse: you will get it wrong. Even when you work hard for half a week; and your code passes all your tests; it will be wrong (if you attempt to create some "generic" solution that works for all kinds of dates). – GhostCat Apr 22 '16 at 08:29
  • I have to pass value to Javascript form as string. Example, today is 2016-04-22. I need to pass 2016-03-01 to form. I get year that I need, month that I need and day that I need. How to combine 20016, 03 and 01 in String to get "2016-03-01"? – Dainius Java Apr 22 '16 at 08:56

2 Answers2

1

While you should definitely follow @Tunaki's advise on how to format a Date, I think the real problem lies elsewhere.

System.out.println("03".concat("-").concat("10").concat("-01"));

Here the output will be 03-10-01 and not -8 (your example gives a similar output).

You mentioned in one of your comments:

I have to pass value to Javascript form as string.

I guess that's where the real problem lies. For example, if the resulting JavaScript ends up looking something like this:

var myDate = 2016-03-01 ;

The expression will be evaluated and myDate will end up as a number with the value 2012. You will have to make sure you're passing a string and not a number.

nyname00
  • 2,496
  • 2
  • 22
  • 25
0

The right answer is: Java

LocalDate today = LocalDate.now();
LocalDate prevMonthFirstDay = today.minusMonths(1).withDayOfMonth(1);
LocalDate prevMonthLastDay = prevMonthFirstDay.plusMonths(1).minusDays(1);

Javascript

var f = document.forms['SearchForm'];
f.startdate.value = "<%=prevMonthFirstDay.toString()%>"
f.enddate.value = "<%=prevMonthLastDay.toString()%>"

Special thanks to all those who "helped" me putting minuses.

Dainius Java
  • 125
  • 1
  • 4
  • 14