Convert a date time from xml to unix timestamp - Android java.util

Android examples for java.util:Date Timestamp

Description

Convert a date time from xml to unix timestamp

Demo Code


//package com.java2s;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    /**//from  ww w.java2 s . c  om
     * {@link DateFormat} for parsing a date via rest service in the format:
     * 2011-08-20T19:47:30+01:00
     */
    private static SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd'T'HH:mm:ssZ");

    /**
     * Convert a datetime from xml to unix timestamp
     * @param datetime
     * @return
     * @throws ParseException 
     */
    public static long toUnixTimestamp(String datetime)
            throws ParseException {
        return toUnixtimeTimestamp(dateFormat.parse(datetime));
    }

    /**
     * Create an unix timestamp of a date object
     * @param date
     * @return seconds since 1970-1-1
     */
    public static Long toUnixtimeTimestamp(Date date) {
        if (date == null) {
            return null;
        }
        return date.getTime() / 1000L;
    }
}

Related Tutorials