2

I have stored date in a string. Now I want to get minutes from the date string. How can I convert it into minutes?

Here is how I stored in a class:

    public String fromDate;
    public String toDate;

I have set getter and setter methods. I have saved the date value now I want to retrive the value and convert to minutes.

Retriving Like this:

  Calendar c  = Calendar.getInstance();

  String datefrom = eventData.getFromDate();

I tried using this calendar instance:

 c.set(Calendar.HOUR, hour);
            c.set(Calendar.MINUTE, minute);
            c.set(Calendar.DATE,day);
            Date datefrom = c.getTime();
            startTime = String.valueOf(datefrom);
            int hour = c.get(Calendar.HOUR);
            int totalMinutes = hour * 60;

But this I can get from Date object. I have stored date in String format. How can I convert this?

5 Answers5

3

Use Joda-Time:

String fromDate;
String toDate;
DateTimeFormatter format = new DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime fromDT = format.parseDateTime(fromDate);
DateTime toDT = format.parseDateTime(toDate);
Duration duration = new Duration(fromDT, toDT);
int minutes = duration.getStandardMinutes();

To import in Android Studio, update your build.gradle file:

apply plugin: 'android'
dependencies {
   compile 'joda-time:joda-time:2.4'
   compile 'joda-time:joda-time:2.2'

}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Kristy Welsh
  • 7,828
  • 12
  • 64
  • 106
2

To convert a String to Date in Java you would have to use the DateFormat like the sample below:

String string = "January 26, 2016";
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date); // Tue Jan 26 00:00:00 GMT 2016

then you can go ahead with your Calendar implementation.

Johan Duke
  • 199
  • 6
  • Thank you for answer .. getting unhandled exception error on format.parse method. @Johan Duke.. –  Jan 26 '16 at 14:46
  • even if this doesn't solve your exception you should put your code inside a try - catch block. you are probably getting an exception because your parsing a String with a different format that the one your setting in the SimpleDateFormat, so you gotta be coherent with the formatted String. if you provide an example of the String your trying to format i will help you out with the code. – Johan Duke Jan 26 '16 at 14:53
1

Usually i'd suggest to parse the time with a SimpleDateFormat, but I think in this case (since the dates seem to have a defined form and there might be problems with the timezones) i'll suggest to retrieve the information yourself:

String date = "Wed Jan 27 07:25:29 GMT+05:30 2016";
String[] times = date.substring(11, 16).split(":");
int minutes = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
System.out.println(minutes);
  • The part date.substring(11, 16) extracts the hours and minutes part from the string ("07:25").
  • The part .split(":"); splits the string "07:25" into two strings: "07" and "25".
  • after that you just parse those numbers to integers with Integer.parseInt(...) and calculate the number of minutes!
ParkerHalo
  • 4,341
  • 9
  • 29
  • 51
0

To get the minutes from a String is possible to use a DateFormat to convert the string to a Date and after use your code.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/11033348) – duffy356 Jan 26 '16 at 15:54
  • 1
    This answer shows the process to pass from String to Date than extracting minutes from Date. It doesn't show the code, only the process, so it is an answer. It depends from who is asking the question if it is better to show the code or only the logical steps, I thought that here was better showing the logic, not the code. But others also helped the OP with concrete code. – Davide Lorenzo MARINO Jan 26 '16 at 15:58
0

Your Question is really two questions:

  • How to parse a String to get a date-time object
  • How to get number of minutes since start-of-day from a date-time object

The first one, parsing a String into a date-time, has been covered at least 1,845 times on Stack Overflow, so I will skip it. The second Question is addressed below.

Please try to make your questions more clear. And focus on a single topic as narrowly as possible, as that is the intention for Stack Overflow.

Minutes-Of-Day

What you seem to want is called “Minutes-Of-Day”, the number of minutes since the start of the day.

Be careful and thoughtful here as there are two different definitions for minutes-of-day. You can get the actual number of minutes for a specific day in a specific time zone. Or you can calculate for a generic 24-hour day. Because of Daylight Saving Time (DST) and other anomalies, a day is not necessarily 24 hours long. For example, in most of the United States the use of DST means a day may be 23, 24, or 25 hours long.

The Question’s code and other Answers ignore the crucial issue of time zone (a common mistake in date-time work). If you do not specify a time zone, your JVM’s current default time zone is silently applied. Not good… that default can change at any moment, even during runtime! Better to always specify the time zone you expect/desire.

Avoid Old Date-Time Classes

The old date-time classes bundled with the earliest versions of Java are notoriously troublesome. Avoid them. Instead use the java.time framework built into Java 8 and later (see Tutorial). If that technology is not available to you, use the Joda-Time library (which inspired java.time). Examples below are in java.time in Java 8 Update 66.

java.time

Let’s look at March 3rd, 2015. This day was the "Spring ahead" DST changeover day for most of the United States. The clock jumped from 2 AM to 3 AM. So 03:00:00.0 on this day meant two hours (120 minutes) actually elapsed since the start of the day. If we treat this as a generic 24-hour day, we would say three hours (180 minutes) elapsed. The java.time classes can calculate minutes-of-day in both definitions.

First we get 3 AM on that changeover day. We use one of the time zones which recognized DST.

ZoneId zoneId = ZoneId.of ( "America/Los_Angeles" );
ZonedDateTime zdt = ZonedDateTime.of ( 2015 , 3 , 8 , 3 , 0 , 0 , 0 , zoneId );

Generic 24-Hour Day

Next we get the minutes since start of day assuming a generic 24-hour day. The ChronoField enum provides many ways to access TemporalField values such as MINUTE_OF_DAY.

long minutesOfDayForGeneric24HourDay = zdt.get ( ChronoField.MINUTE_OF_DAY );

Actual Day

To get the actual number of minutes elapsed since the start of this particular day for this particular time zone in which DST was changing over, we must do a bit more work. We have to determine the first moment of the day from which we can calculate elapsed time. To get that first moment, we must go through the LocalDate class which is a date-only value without time-of-day nor time zone. On that LocalDate object we call atStartOfDay to adjust back into a date-time value (a ZonedDateTime). You might think you could skip this by assuming the day starts at 00:00:00.0 but that is not always true.

ZonedDateTime zdtStart = zdt.toLocalDate ().atStartOfDay ( zoneId );

Now calculate elapsed time. The Duration class represents a span of time as hours, minutes, and seconds. From that Duration we can ask the total number of minutes, converting hours to minutes.

Duration duration = Duration.between ( zdtStart , zdt );
long minutesOfDayForActualDay = duration.toMinutes ();

Dump to console. Note how the generic ChronoField approach says 180 minutes while the actual Duration approach yields 120 minutes.

System.out.println ( "zdt: " + zdt + " | minutesOfDayForGeneric24HourDay: " + minutesOfDayForGeneric24HourDay + " | duration: " + duration + " | minutesOfDayForActualDay: " + minutesOfDayForActualDay );

zdt: 2015-03-08T03:00-07:00[America/Los_Angeles] | minutesOfDayForGeneric24HourDay: 180 | duration: PT2H | minutesOfDayForActualDay: 120

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154