0

Based on How to convert Standard Date into minutes in java? information, I follow this technique to convert date into minute, but an output is not as an expected value (e.g., 12 hour -> it should be 720 minutes).

Here is my source code

    SimpleDateFormat sdf = new SimpleDateFormat("hh");
    Date theDate = sdf.parse ("12");
    long minutes22 = (theDate.getTime() / 1000)  / 60;
    System.out.println("Minute "+minutes22);

An output is -420. Can someone explain to me ?

< First problem is solved, please take a look at the comment section >

The new problem is cutting String. < The problem is solved as well,please take a look at comment section >

For Another Input that I have try to do my own solution,but there is problem occur after finishing cutting String. I found that duplicate value can not keep separately. I don t know why would happen because I kept in different index. Any suggestion ?

Here is another my another source code.

    String date = "Sun 10:00-20:00\r\n" + 
            "Fri 05:00-10:00\r\n" + 
            "Fri 16:30-23:50\r\n" + 
            "Sat 10:00-24:00\r\n" + 
            "Sun 01:00-04:00\r\n" + 
            "Sat 02:00-06:00\r\n" + 
            "Tue 03:30-18:15\r\n" + 
            "Tue 19:00-20:00\r\n" + 
            "Wed 04:25-15:14\r\n" + 
            "Wed 15:14-22:40\r\n" + 
            "Thu 00:00-23:59\r\n" + 
            "Mon 05:00-13:00\r\n" + 
            "Mon 15:00-21:00";

    List<String> Hour = new ArrayList<String>();
    int loop = 0;

    String [] replacement = {"sun","mon","tue","wed","thu","fri","sat"};
    String new_s = date.toLowerCase().replaceAll(" ","");

    for(int j = 0;j<replacement.length;j++)
    {
        new_s = new_s.replace(replacement[j],"").replace("\r\n","");


    }

    String temp = "";
    temp = temp+new_s.replaceAll("-","");

    int show = 0;
    while(!temp.equals(""))
    {
        Hour.add(temp.substring(loop,loop+5));
        temp = temp.replace(temp.substring(0,loop+5),"");
        System.out.println("Hour "+Hour.get(show));
        show++;

    }

Here is the output

Hour 10:00 Hour 20:00 Hour 05:00 Hour 16:30 Hour 23:50 Hour 24:00 Hour 01:00 Hour 04:00 Hour 02:00 Hour 06:00 Hour 03:30 Hour 18:15 Hour 19:00 Hour 04:25 Hour 15:14 Hour 22:40 Hour 00:00 Hour 23:59 Hour 13:00 Hour 15:00 Hour 21:00

Another question - why would it print out < 0 instead of 1200 >

 LocalTime froms = LocalTime.parse("20:00", DateTimeFormatter.ofPattern("HH:mm", Locale.ENGLISH));
System.out.println("TIme "+froms.getMinute());'
Mr.Kim
  • 186
  • 1
  • 10
  • 3
    Could it be a timezone issue? – Sentry May 19 '18 at 16:01
  • 2
    Can also try TimeUnit.HOURS.toMinutes(12) // 720 – CodeMonkey May 19 '18 at 16:04
  • 4
    Try to print the date and you will see the problem, the parsing produces a wrong date. Change `hh` to `HH` will make it (up to timezone issue). – Jean-Baptiste Yunès May 19 '18 at 16:04
  • 1
    Take a look at [this answer](https://stackoverflow.com/a/15003833/9524541) – SystemGlitch May 19 '18 at 16:05
  • @JasonM1 Thank you!! . TimeUnit solved this problem. It could be timezone issue as Sentry and Jean 's comment. – Mr.Kim May 19 '18 at 16:20
  • @Juan I am just confused about an output because I try to look solution serveral times in order to convert into minute ,so that might not related to calculation. – Mr.Kim May 19 '18 at 16:24
  • @SystemGlitch Thanks a lot . – Mr.Kim May 19 '18 at 16:27
  • 1
    Is there a reason you still use the old Date API ( `Date`) instead of the new one (`LocalDate`, `LocalDateTime`, ...)? – Zabuzard May 19 '18 at 16:43
  • @Zabuza I found Date API that solved the problem with a format. I want to solve an input String which is something like "Sun 11:00-20:00" then cutting a String to calculate the minute between 11.00-20.00. There's nothing to use old API but I found this one is a basic. If you have any idea please tell me. . – Mr.Kim May 19 '18 at 17:00

2 Answers2

5

tl;dr

Duration.ofHours(12).toMinutes()

720

java.time.Duration

You are using troubled old legacy date-time classes. And furthermore, you are abusing by them.

The Date class has been replaced by the Instant class. Both represent a moment, a point on the timeline. Do not abuse them to represent “twelve hours”.

Apparently you want to represent a span of time unattached to the timeline. So use the class designed for that purpose, Duration.

Duration d = Duration.ofHours(12);

To see the total number of minutes in the entire duration, call toMinutes.

long minutes = d.toMinutes();

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
2
    String input = "Sun 11:00-20:00";
    String[] fromAndTo = input.split("-");
    LocalTime from = LocalTime.parse(fromAndTo[0], DateTimeFormatter.ofPattern("EEE H:mm", Locale.ENGLISH));
    LocalTime to = LocalTime.parse(fromAndTo[1]);
    System.out.println(Duration.between(from, to).toMinutes());

This printed:

540

Can someone explain to me ?

You’ve got two bugs that both contribute to your incorrect result:

  • You misused a Date for a duration and didn’t specify time zone.
  • You used lowercase hh for hours in you format pattern string. hh is for hour within AM or PM from 01 through 12, so 12 means the same as 0 (because 12:00 AM is the same as 00:00 on a 24-hour clock).

Your SimpleDateFormat understood 12 as 00:00 in your local time zone (as defined by your JVM’s time zone setting). However, when you take out the milliseconds using theDate.getTime(), you get the milliseconds since 00:00 in UTC. Since your time zone has an offset from UTC, you get an error the magnitude of this offset.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • @V.V I have try to use split("-") with another input type such as String date = "Sun 10:00-20:00\r\n" + "Fri 05:00-10:00\r\n" + "Fri 16:30-23:50\r\n" + "Sat 10:00-24:00\r\n" + "Sun 01:00-04:00\r\n" + "Sat 02:00-06:00\r\n" + "Tue 03:30-18:15\r\n" + "Tue 19:00-20:00\r\n" + "Wed 04:25-15:14\r\n" + "Wed 15:14-22:40\r\n" + "Thu 00:00-23:59\r\n" + "Mon 05:00-13:00\r\n" + "Mon 15:00-21:00"; < but It does not cut all of period > Am I using split in the wrong way ?? – Mr.Kim May 20 '18 at 04:59
  • 1
    Probably. In that case I would split on "\r\n" (or "[\r\n]+") first to split into lines, and then each line on "-". – Ole V.V. May 20 '18 at 05:57
  • Nice Method, but there is problem occur after finishing cutting String. I found that duplicate value can not keep separately [ In case of different day,but same period time]. I dont know why would happen because I kept in different index. Any suggestion ? – Mr.Kim May 20 '18 at 12:21
  • @Mr.Kim No suggestions without seeing your code. You may consider posting a new question? BTW `LocalTime.parse` won’t work for end time 24:00 either. – Ole V.V. May 20 '18 at 12:26
  • `temp.replace(temp.substring(0,loop+5),"")` replaces *all* occurrences of the time in question (not just the first). – Ole V.V. May 20 '18 at 13:12
  • Ok so i have to change to another solution. Thanks a lot Is there any reccommend or suggestion for source code ? – Mr.Kim May 20 '18 at 13:16
  • 1
    An immediate suggestion would be `temp = temp.substring(5);`. But depending on your exact requirements I think that splitting on `"\r\n"` and then using the code in the answer would be better. – Ole V.V. May 20 '18 at 13:21
  • V.V I have to try your solution with "20:00" but change a little bit something like LocalTime froms = LocalTime.parse("20:00", DateTimeFormatter.ofPattern("HH:mm", Locale.ENGLISH)) then use getMinute() . But It turns out of 0 minute instead of 1200 minutes. Why that does not 1200 ? Beacuse of What ? – Mr.Kim May 20 '18 at 15:10
  • Excuse me, sorry, I can say nothing about errors in your code when I cannot see your code. – Ole V.V. May 20 '18 at 15:14
  • 1
    `20:00` means that the hour of day is 20 and the minute of the hour is 0. So `froms.getHour()` gives you 20 and `froms.getMinute()` gives you 0. Your parsing is correct and you have got the expected `LocalTime` value. – Ole V.V. May 20 '18 at 15:35
  • How can I convert "20.30" to "1230" minute ? Using Duration as your answer is possible ? – Mr.Kim May 20 '18 at 15:42
  • 1
    I think I got It !! Using Duration.between("00:00" to "20:30") ?? – Mr.Kim May 20 '18 at 15:47
  • 1
    That should work, @Mr.Kim. Try it. "00:00" can be stated as `LocalTime.MIN` or `LocalTime.MIDNIGHT` (whichever you prefer). – Ole V.V. May 20 '18 at 17:33