Check if 24 hours have passed (reading from a string)

后端 未结 4 1891
醉话见心
醉话见心 2021-01-28 04:37

I am saving date\'s in a file in the following format as a string.

Sat Jul 21 23:31:55 EDT 2012

How can I check if 24 hours have passed? I am a

4条回答
  •  失恋的感觉
    2021-01-28 05:26

    You can do something like this:

    try {
    
        // reading text...
        Scanner scan = new Scanner( new FileInputStream( new File( "path to your file here..." ) ) );
        String dateString = scan.nextLine();
    
        // creating a formatter.
        // to understand the format, take a look here: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
        // EEE: Day name of week with 3 chars
        // MMM: Month name of the year with 3 chars
        // dd: day of month with 2 chars
        // HH: hour of the day (0 to 23) with 2 chars
        // mm: minute of the hour with 2 chars
        // ss: second of the minute with 2 chars
        // zzz: Timezone with 3 chars
        // yyyy: year with 4 chars
        DateFormat df = new SimpleDateFormat( "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US );
    
        // parsing the date (using the format above, that matches with your date string)
        Date date = df.parse( dateString );
    
        // now!
        Date now = new Date();
    
        // gets the differente between the parsed date and the now date in milliseconds
        long diffInMilliseconds = now.getTime() - date.getTime();
    
        if ( diffInMilliseconds < 0 ) {
            System.out.println( "the date that was read is in the future!" );
        } else {
    
            // calculating the difference in hours
            // one hour have: 60 minutes or 3600 seconds or 3600000 milliseconds
            double diffInHours = diffInMilliseconds / 3600000D;
            System.out.printf( "%.2f hours have passed!", diffInHours );
    
        }
    
    } catch ( FileNotFoundException | ParseException exc ) {
        exc.printStackTrace();
    }
    

提交回复
热议问题