Last active
August 29, 2015 13:56
-
-
Save bgulla/8956951 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This is a quick tutorial on how to learn dates for CS631. I am not trying to aid in your project but provide some more | |
* insight on how I like to use the Java Date Object. | |
* | |
* NOTE: I just realized that it seems like he wants us to use DateFormatter & Gregorian Calendar, so don't use SimpleDateFormat but the | |
* concepts behind it should be similar. | |
* | |
*/ | |
public void learnDates() throws Exception{ | |
/** | |
* Dates are stored as longs. The long number represents the number of milliseconds since JAN01-1970. Dates should always be worked | |
* with as Dates and not their String representations because it is easier to compare/modify and they require less memory. | |
*/ | |
// Create a date object with the current date and time. | |
Date dateRightNow = new Date(System.currentTimeMillis()); | |
/** | |
* Since dates are stored as longs (under the hood), you can get a lot of information out of them in any way you want. To learn more of the | |
* formatting, look up the SimpleDateFormat parsing inputs. | |
*/ | |
final String DATE_FORMAT = "yyyy-mm-dd HH:mm:ss"; | |
// Create the date formatter so we can parse the date | |
SimpleDateFormat dateFormatter = new SimpleDateFormat(DATE_FORMAT); | |
// Now we want a fancy representation of the Date object we just created | |
String nowAsString = dateFormatter.format(dateRightNow); | |
System.out.println(nowAsString); // prints 2014-02-12 09:48:00 if it was right now | |
// Now say we want to take a string representation of a date we already have and turn it into a String. | |
Date dateInThePast = dateFormatter.parse("2014-02-06 12:12:13"); | |
// now we have a date object that we can store in our class. | |
// Now if you wanted to compare dates, use their long values | |
if( dateInThePast.getTime() < dateRightNow.getTime() ) | |
{ | |
// do something. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment