Convert string Date into timestamp in Android?

2019-01-09 01:17发布

问题:

I want to convert my date (which is in String format), e.g. 13-09-2011, into Timestamp. I used below code but I got the 2011-09-13 00:00:00.0 as a result. But I want Timestamp like,1312828200000 format.

I cannot understand how to convert that.

My code:

String str_date="13-09-2011";
DateFormat formatter ; 
Date date ; 
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date); 
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
System.out.println("Today is " +timeStampDate);

回答1:

If you use getTime() of Date object you will get time in millisecond. No need to use Timestamp to get your result.

String str_date="13-09-2011";
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = (Date)formatter.parse(str_date); 
System.out.println("Today is " +date.getTime());

The above code will print something like 1312828200000 you need and this is long value.



回答2:

String str_date=month+"-"+day+"-"+yr;
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date date = (Date)formatter.parse(str_date); 
long output=date.getTime()/1000L;
String str=Long.toString(output);
long timestamp = Long.parseLong(str) * 1000;


回答3:

This line:

"Today is " +timeStampDate

calls TimeStamp.toString() method "which Formats a timestamp in JDBC timestamp escape format. yyyy-mm-dd hh:mm:ss.fffffffff, where ffffffffff indicates nanoseconds."

The TimeStamp you got internally has the value you want. If you want to get it than use: System.out.println("Today is " + timeStampDate.getTime());

    String str_date="13-09-2011";
    DateFormat formatter ; 
    Date date ; 
    formatter = new SimpleDateFormat("dd-MM-yyyy");
    date = (Date)formatter.parse(str_date);
    java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
    System.out.println("Today is " + timeStampDate.getTime());

Or if you don't need the Timestamp, you can directly use date.getTime(). It "Returns the Date as a millisecond value.":

    String str_date="13-09-2011";
    DateFormat formatter ; 
    Date date ; 
    formatter = new SimpleDateFormat("dd-MM-yyyy");
    date = (Date)formatter.parse(str_date);
    System.out.println("Today is " + date.getTime());


回答4:

It may can help you

    long time= System.currentTimeMillis();//timestamp in milliseconds of current time


    String tp = Long.toString(time);//use timestamp as a string


回答5:

tl;dr

Use modern java.time classes.

LocalDate.parse( 
    "13-09-2011" , 
    DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) 
)
.atStartOfDay(
    ZoneId.of( "Africa/Casablanca" )  // Or use `ZoneOffset.UTC` instead of a zone.
)
.toInstant()
.toEpochMilli()

See this code run live at IdeOne.com.

1315872000000

Details

Apparently you want to represent the first moment of a particular date as a count of milliseconds since the epoch reference of first moment of 1970 in UTC.

java.time

The modern approach uses the java.time classes that years ago supplanted the troublesome legacy classes such as Date, Calendar, and SimpleDateFormat.

First parse your input string as a LocalDate, for a date-only value without time-of-day and without time zone.

Tip: Rather then using such custom formats when exchanging date-time values as text, use standard ISO 8601 formats. The java.time classes use them by default when parsing/generating strings.

String input = "13-09-2011" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
LocalDate ld = LocalDate.parse( input , f ) ;

Determine the first moment of the day on that date. Doing so requires a time zone. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;

Never assume the day starts at 00:00. In some zones on some dates, the day may start at another time such as 01:00. Let java.time determine first moment.

ZonedDateTime zdt = ld.startOfDay( z ) ;  // Determine first moment of the day on this date in this zone. May not be 00:00.

Adjust to UTC from that zone by extracting a Instant.

Instant instant = zdt.toInstant() ;

Get a count of milliseconds since 1970-01-01T00:00Z. Beware of possible data loss, as an Instant carries a finer resolution of nanoseconds. Any microseconds or nanoseconds will be ignored.

long millisecondsSinceEpoch = instant.toEpochMilli() ;

You can go back the other direction, from a count-from-epoch to a Instant.

Instant instant = Instant.ofEpochMilli( millisecondsSinceEpoch) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….