-2

I have a date in the format 07/18/2018 01:00-04:00 CDT in a String variable. where 01:00-04:00 is a time range. I need convert this into a date format in two separate variables keeping timezone in mind.

Var1 should have 07/18/2018 01:00 CDT Var2 should have 07/18/2018 04:00 CDT

Should i tokenize this string and seperate out 01:00-04:00? or is there a way in simpleDateParser to this?

xingbin
  • 27,410
  • 9
  • 53
  • 103
chingupt
  • 403
  • 2
  • 7
  • 19
  • No, you should implement it ad-hoc. – NiVeR Sep 27 '18 at 07:44
  • could you give some more details on what you mean by ad-hoc? – chingupt Sep 27 '18 at 07:45
  • 1
    As you said, split, concat, and convert to java date. – NiVeR Sep 27 '18 at 07:45
  • yeah, that was my initial thought also... i tried with SimpleDateParser, but doesnt work. DateFormat formatter=new SimpleDateFormat("MM/dd/yyyy HH:mm-HH:mm"); Date date=formatter.parse(dateTested); this turns out to give date as Wed Jul 18 04:00:00 IST 2018and completely forgets about 01:00. – chingupt Sep 27 '18 at 07:47
  • 1
    Your necessity is not standard so it is not present in standard libraries – NiVeR Sep 27 '18 at 07:48

2 Answers2

3

I have a date in the format 07/18/2018 01:00-04:00 CDT in a String variable.

Since the input string is not in standard date/time format, you need split the string to two strings then parse them separatly:

String input = "07/18/2018 01:00-04:00 CDT";

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm z");

// parse 07/18/2018 01:00 CDT
ZonedDateTime first = ZonedDateTime.parse(input.replaceAll("-\\d{2}:\\d{2}", ""), formatter); 

// parse 07/18/2018 04:00 CDT
ZonedDateTime second = ZonedDateTime.parse(input.replaceAll("\\d{2}:\\d{2}-", ""), formatter); 
xingbin
  • 27,410
  • 9
  • 53
  • 103
1

The problem is that what you have is not a datetime. It is an interval. A datetime formatter is not going to be able to cope with it. The formatter APIs produce a Date object (for the legacy DateFormat classes) or a TemporalAccessor object (for DateTimeFormatter). There is no direct support for intervals in either the current or legacy Java date / time APIs.

Given that the format / formatter classes can't return an interval, it is not surprising that the format strings don't support this1.

So, the only alternative is to do some parsing / string bashing yourself. @Sun's answer is one solution.


1 - If you could write a format / formatter pattern that tell the parser to "ignore the next 5 characters" for example, you could create two different formatters that parsed your example to extract the first datetime and the second datetime. But you can't. One reason is that this approach would not work for formatting.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216