Simon Verbeke
Simon Verbeke

Reputation: 3005

Simple DateTime class in Java

So I've been going over some of the date classes in java and in popular libraries, and they all seem overly bloated, or are too bugged/complicated for me to use. The closest I've found is Java's Calendar class. But it's still too complicated. So I'm looking for a super simple DateTime class.

I need this for an Android app I'm currently working on. In this app I read a week schedule from a website to display in my app. So all I need is:

Second and millisecond precision are not necessary. I also don't need timezones, since the app is only for my current college. The only support I need for special cases is:

I know already that someone will probably suggest Joda-Time, but it's bloated, and I've read multiple reports about how slow it is on Android.

Upvotes: 1

Views: 5094

Answers (7)

Basil Bourque
Basil Bourque

Reputation: 338326

Avoid legacy date-time classes

overly bloated, or are too bugged/complicated

Date and Time classes are not simple because date-time handling is not simple. You may think intuitively that date-time work is easy, but no, it is surprisingly slippery and tricky until you understand some basic concepts.

suggest Joda-Time

The Joda-Time project was the industry-leading date-time framework. Until its creator Stephen Colebourne went on to lead the JSR 310 to add a built-in date-time library into Java 8+. The java.time classes are the official successor to Joda-Time which is now in maintenance-mode.

how slow [Joda-Time] is on Android

Android 26 and later comes with an implementation of java.time.

For earlier Android, the latest tooling provides most of the java.time functionality via “API desugaring”.

Java's Calendar class.

That terribly flawed class is now legacy. Never use Calendar, Date, SimpleDateFormat, and so on.

Importance of time zones

I also don't need timezones, since the app is only for my current college.

Actually, you do need time zones.

For one thing, determining today's date requires a time zone. For any given moment, the date varies around the globe by time zone. At any moment, it is “tomorrow” in Tokyo Japan while simultaneously “yesterday” in Toledo Ohio US.

For another thing, if you want to calculate durations of time, such as your scheduling-app tracking when an office will be open and closed, you need to account for time zone related anomalies such as Daylight Saving Time (DST) cut-overs.

java.time

years months days hours minutes

To represent a date with time-of-day, use LocalDateTime class.

LocalDateTime ldt = LocalDateTime.of( 2025 , 1 , 23 , 15 , 45 ) ;

But as I said, do not use that to represent a moment, a point on the timeline. For a moment, add a time zone to get a ZonedDateTime.

LocalDate ld = LocalDate.of( 2025 , 1 , 23 ) ;
LocalTime lt = LocalTime.of( 15 , 45 ) ;
ZonedId z = ZoneId.of( "America/Edmonton" ) ;
ZonedDateTime zdt = LocalDateTime.of( ld , lt , z ) ;

Upvotes: 1

Felipe Andrade
Felipe Andrade

Reputation: 521

I have this helper classes:

https://gist.github.com/feandrad/06f0e00538e245a2afb3787d4144e034

  • DateTime.java Static class with some common operations
  • SimpleDate.java: Class that handles Year, Month, Day of the month (Support leap year)
  • SimpleTime.java Class that handles Hour, Minute, Seconds, Milliseconds

I made those classes some time ago, hope it helps someone. Be free to contribute if you want to.

Upvotes: 0

Simon Verbeke
Simon Verbeke

Reputation: 3005

As suggested by Sebastiaan van den Broek, I decided to make my own simple class for storing dates and times. If anyone should need it, I included the code.

Be aware that there's only support for storing dates and times generated by a system that accounts for leap years, time zones, etc. There are probably also a couple of functions missing for simple storage, but this class is - at the moment - sufficient for my case.

/**
 * A simple class for storing dates and times.
 * There is no support for time zones, leap years, etc.
 * So only use this when you're certain the dates and times you're storing are generated with special cases in mind.
 * @author Simon
 *
 */
public class SimpleDateTime 
{
    int year;
    int month;
    int day;
    int hour;
    int minute; 


    /**
     * Construct a simple date and time object
     * @param year
     * @param month
     * @param day
     * @param hour
     * @param minute
     */
    public SimpleDateTime(int year, int month, int day, int hour, int minute) {
        super();
        this.year = year;
        this.month = month;
        this.day = day;
        this.hour = hour;
        this.minute = minute;
    }

    /**
     * Construct a simple date object, with time component initialised to 0
     * @param year
     * @param month
     * @param day
     */
    public SimpleDateTime(int year, int month, int day) {
        super();
        this.year = year;
        this.month = month;
        this.day = day;
        this.hour = 0;
        this.minute = 0;
    }

    /**
     * Construct a simple time object, with date component initialised to 0
     * @param hour
     * @param minute
     */
    public SimpleDateTime(int hour, int minute)
    {
        super();
        this.year = 0;
        this.month = 0;
        this.day = 0;
        this.hour = hour;
        this.minute = minute;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    public int getHour() {
        return hour;
    }

    public void setHour(int hour) {
        this.hour = hour;
    }

    public int getMinute() {
        return minute;
    }

    public void setMinute(int minute) {
        this.minute = minute;
    }   

    public String toDateString()
    {
        return day + "/" + month + "/" + year;
    }

    public String toTimeString()
    {
        return hour + ":" + minute;
    }

    /**
    * Parses a date from a string to a {@link SimpleDateTime} object.
    * Can handle various delimiters, as in these examples:
    * <ul>
    * <li>15/10/1993</li>
    * <li>15-10-1993</li>
    * <li>15.10.1993</li>
    * </ul>
    * It can also handle mixed delimiters as in these examples:
    * <ul>
    * <li>15/10.1993</li>
    * <li>15-10/1993</li>
    * <li>15.10-1993</li>
    * <li>etc.</li>
    * </ul>
    * @param date the string to parse
    * @return
    */
    public SimpleDateTime parseDate(String date)
    {
        String[] dateParts = date.split("[-\\.:]");
        int day = Integer.parseInt(dateParts[0]);
        int month = Integer.parseInt(dateParts[1]);
        int year = Integer.parseInt(dateParts[2]);

        return new SimpleDateTime(year, month, day);
    }




    /**
    * Parses a time from a string to a {@link SimpleDateTime} object.
    * Can handle various delimiters, as in these examples:
    * <ul>
    * <li>20.07</li>
    * <li>20:07</li>
    * <li>20-07</li>
    * </ul>
    * @param time the string to parse
    * @return
    */
    public SimpleDateTime parseTime(String time)
    {
        String[] timeParts = time.split("[-\\.:]");
        int hours = Integer.parseInt(timeParts[0]);
        int minutes = Integer.parseInt(timeParts[1]);

        return new SimpleDateTime(hours, minutes);
    }
}

Upvotes: 0

EdGs
EdGs

Reputation: 356

Date is deprecated...generally. Use Calendar or as suggested Joda Time

Calendar calendar = Calendar.getInstance();
int Year = calendar.get(Calendar.YEAR);
int Month = calendar.get(Calendar.MONTH + 1);
int Day = calendar.get(Calendar.DAY_OF_MONTH);

Upvotes: 0

lugonja
lugonja

Reputation: 313

you can use this:

Date todayDate = new Date();
todayDate.getDay();
todayDate.getHours();
todayDate.getMinutes();
todayDate.getMonth();
todayDate.getTime();

EDIT:

better way to do is to use Calendar:

Calendar cal = Calendar.getInstance(); 

int millisecond = cal.get(Calendar.MILLISECOND);
int second = cal.get(Calendar.SECOND);
int minute = cal.get(Calendar.MINUTE);
    //12 hour format
int hour = cal.get(Calendar.HOUR);
    //24 hour format
int hourofday = cal.get(Calendar.HOUR_OF_DAY);

Same goes for the date, as follows:

Calendar cal = Calendar.getInstance(); 

int dayofyear = cal.get(Calendar.DAY_OF_YEAR);
int year = cal.get(Calendar.YEAR);
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
int dayofmonth = cal.get(Calendar.DAY_OF_MONTH);

Upvotes: 1

Jeff Kidzie
Jeff Kidzie

Reputation: 1

Try this:

Calendar calendar = Calendar.getInstance();
    int date = calendar.get(Calendar.DATE);
    int month = calendar.get(Calendar.MONTH);
    int year = calendar.get(Calendar.YEAR);

Upvotes: 0

Sebastiaan van den Broek
Sebastiaan van den Broek

Reputation: 6331

You do need time zones because you probably do or did have daylight savings time in your country. I highly recommend reading http://www.odi.ch/prog/design/datetime.php to get a basic understanding of how this will affect you.

It's just better to properly implement this 'cause it will bite you in the ass later if you don't.

Upvotes: 0

Related Questions