Java Second Format getSecondsSince(String rfc1123Date)

Here you can find the source of getSecondsSince(String rfc1123Date)

Description

get Seconds Since

License

Apache License

Parameter

Parameter Description
rfc1123Date date and time in RFC-1123 format (e.g. "Sun, 06 Nov 1994 08:49:37 GMT")

Return

the number of seconds that have passed since the given date

Declaration

public static int getSecondsSince(String rfc1123Date) 

Method Source Code


//package com.java2s;
/*/*from   ww w . j ava2s .  c o  m*/
 * #%L
 * wcm.io
 * %%
 * Copyright (C) 2014 wcm.io
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class Main {
    private static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
    private static final TimeZone GMT_TIME_ZONE = TimeZone.getTimeZone("GMT");

    /**
     * @param rfc1123Date date and time in RFC-1123 format (e.g. "Sun, 06 Nov 1994 08:49:37 GMT")
     * @return the number of seconds that have passed since the given date
     */
    public static int getSecondsSince(String rfc1123Date) {

        Date reference = parse(rfc1123Date);
        Date now = new Date();

        return (int) ((now.getTime() - reference.getTime()) / 1000L);
    }

    /**
     * @param rfc1123Date date and time in RFC-1123 format (e.g. "Sun, 06 Nov 1994 08:49:37 GMT")
     * @return the parsed date
     */
    public static Date parse(String rfc1123Date) {
        try {
            return getDateFormat().parse(rfc1123Date);
        } catch (ParseException e) {
            throw new RuntimeException("Failed to parse date from string " + rfc1123Date, e);
        }
    }

    private static DateFormat getDateFormat() {
        SimpleDateFormat df = new SimpleDateFormat(PATTERN_RFC1123, Locale.US);
        df.setTimeZone(GMT_TIME_ZONE);
        return df;
    }
}

Related

  1. getSecond()
  2. getSecond(Date date)
  3. getSecond(String time)
  4. getSeconds(long time)
  5. getSecondsFormatter()
  6. getStringFromNanoSeconds(final long nanoSeconds, final long format)
  7. getThisSecondTime()
  8. getTimeSecondInteger(Date date)
  9. getToSecond()