2

How do I create a method that retrieve a column of data from database with different values (e.g. 20040804142000, 20040805034000)?

The values are YYYYMMDDHHMMSS and I am suppose to convert them into minutes from 12am. Is there any method to convert all of the data I would require and implement it into my statement.

e.g. output would be

20040805034000 > 220

nevertoolateyet
  • 131
  • 1
  • 3
  • 10
  • `SimpleDateFormat` will allow you to convert the `String` value to a `Date`... – MadProgrammer Apr 22 '15 at 01:55
  • @Satya as for what i've tried, I am trying to use a set of codes from what I found in this website for the conversion. For the retrieval part is mainly where I can't seem to do. – nevertoolateyet Apr 22 '15 at 02:02
  • possible duplicate of [date format and converting that date to JodaTime](http://stackoverflow.com/questions/24324149/date-format-and-converting-that-date-to-jodatime) – Basil Bourque Apr 22 '15 at 08:46

2 Answers2

2

Java 8

So, start with How to parse/format dates with LocalDateTime? (Java 8) and DateTimeFormatter you can convert a String value to a LocalDateTime using something like...

String value = "20040805034000";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
LocalDateTime ldt = LocalDateTime.parse(value, format);
System.out.println(ldt);

Which outputs 2004-08-5T03:40.

Next you can use ChronoUnit.SECONDS.between to calculate the number of seconds between two times, but this means you need an anchor time, which would be midnight in your case...

LocalDateTime midnight = ldt.withHour(0).withMinute(0).withSecond(0).withNano(0);
long seconds = ChronoUnit.SECONDS.between(midnight, ldt);
System.out.println(seconds);

Which outputs 13200

Joda-Time

If you can't use Java 8, then use Joda-Time instead. So starting with Converting a date string to a DateTime object using Joda Time library and Java (Joda): Seconds from midnight of LocalDateTime

String value = "20040805034000";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMddHHmmss");
LocalDateTime dt = formatter.parseLocalDateTime(value);
System.out.println(dt);

LocalDateTime midnight = dt.withMillisOfDay(0);

long seconds = Seconds.secondsBetween(midnight, dt).getSeconds();
System.out.println(seconds);
Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

You could try using libraries like joda-time for this. If you want a more rudimentary answer you could try this:

public int getMinutesSinceMidnight(String s){
    int hour = Integer.parseInt(s.substring(8,10));
    int mins = Integer.parseInt(s.substring(10,12));
    return hour*60+mins;
{
truenite
  • 67
  • 1
  • 8