Adding/Subtracting 5 seconds from Java Date - Showing deprected warning - java

I want to add 5 seconds to current time
Date date = new Date();
date.setSeconds(date.getSeconds()+ 5);
System.out.println("old Value is: "+date);
System.out.println("New Value is: "+ date);
It generates the correct output exactly what I needed as:
Old Value is: Thu Apr 17 14:10:33 PKT 2014
New Value is: Thu Apr 17 14:10:38 PKT 2014
but it gives me a warning error message as
Multiple markers at this line
- The method getSeconds() from the type Date is deprecated
- The method setSeconds(int) from the type Date is
deprecated
What this means. Is it safe to ignore this warning? if not then how to handle it?

you can use date.setTime(date.getTime() + 5000)

You can try this. Calendar is the best solution you are looking at.
Date date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.parse("2014-04-17 14:53:25");
Calendar calendar=Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.SECOND,(calendar.get(Calendar.SECOND)-5));
System.out.println(calendar.getTime());
Out put:
Thu Apr 17 14:53:20 IST 2014

deprecated means that this method should't be used anymore because it can be removed from the Java language in favor of some other method (it probably won't be removed but it's not the preferable way of doing things anymore). Documentation suggests you to use Calendar.get(Calendar.SECOND) which is what you should use in your code.
Note that from Java 8 you can use LocalDateTime#getSecond method again.

Java 8 has completly different time-api and makes handling dates a lot easier. Here's an article
With Java Versions 5-7 (everything below should not be used IMHO) you should use Calendar (as Petr suggested)
If you are allowed to use third-party APIs, you should definitly take a look at JodaTime

showing deprecated warning that means
there is some better way available in java to do so.

java.time
The future visitors of this page are recommended to use java.time API. The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Just local time:
import java.time.LocalTime;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
// ZoneId.systemDefault() returns the time-zone of JVM. Change it as per your
// requirement e.g. to ZoneId.of("Europe/London")
LocalTime localTimeNow = LocalTime.now(ZoneId.systemDefault());
System.out.println(localTimeNow);
// After 5 seconds
LocalTime localTimeAfter5Sec = localTimeNow.plusSeconds(5);
System.out.println(localTimeAfter5Sec);
}
}
Local date & time:
import java.time.LocalDateTime;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
// ZoneId.systemDefault() returns the time-zone of JVM. Change it as per your
// requirement e.g. to ZoneId.of("Europe/London")
LocalDateTime ldtNow = LocalDateTime.now(ZoneId.systemDefault());
System.out.println(ldtNow);
// After 5 seconds
LocalDateTime ldtAfter5Sec = ldtNow.plusSeconds(5);
System.out.println(ldtAfter5Sec);
}
}
Date & time with timezone:
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
// ZoneId.systemDefault() returns the time-zone of JVM. Change it as per your
// requirement e.g. to ZoneId.of("Europe/London")
ZonedDateTime zdtNow = ZonedDateTime.now(ZoneId.systemDefault());
System.out.println(zdtNow);
// After 5 seconds
ZonedDateTime zdtAfter5Sec = zdtNow.plusSeconds(5);
System.out.println(zdtAfter5Sec);
}
}
An instantaneous point on the time-line:
java.time.Instant models a single instantaneous point on the time-line and is independent of timezone. It's most commonly used functions, toEpochMilli and ofEpochMilli are used to convert an instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z, and milliseconds from the epoch of 1970-01-01T00:00:00Z to an instant respectively. Note that Z stands for Zulu and represents UTC+00:00.
import java.time.Instant;
public class Main {
public static void main(String[] args) {
// This moment
Instant now = Instant.now();
System.out.println(now);
// Moment after 5 sec
Instant momentAfter5Sec = now.plusSeconds(5);
System.out.println(momentAfter5Sec);
}
}
Learn more about the modern date-time API from Trail: Date Time.
Joda-time
An excerpt from the Home Page of Joda-Time
Joda-Time is the de facto standard date and time library for Java
prior to Java SE 8. Users are now asked to migrate to java.time
(JSR-310).
Just local time:
import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;
public class Main {
public static void main(String[] args) {
// DateTimeZone.getDefault() returns the time-zone of JVM. Change it as per your
// requirement e.g. to DateTimeZone.forID("Europe/London")
LocalTime localTimeNow = LocalTime.now(DateTimeZone.getDefault());
System.out.println(localTimeNow);
// After 5 seconds
LocalTime localTimeAfter5Sec = localTimeNow.plusSeconds(5);
System.out.println(localTimeAfter5Sec);
}
}
Local date & time:
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
// DateTimeZone.getDefault() returns the time-zone of JVM. Change it as per your
// requirement e.g. to DateTimeZone.forID("Europe/London")
LocalDateTime ldtNow = LocalDateTime.now(DateTimeZone.getDefault());
System.out.println(ldtNow);
// After 5 seconds
LocalDateTime ldtAfter5Sec = ldtNow.plusSeconds(5);
System.out.println(ldtAfter5Sec);
}
}
Date & time with timezone:
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public class Main {
public static void main(String[] args) {
// DateTimeZone.getDefault() returns the time-zone of JVM. Change it as per your
// requirement e.g. to DateTimeZone.forID("Europe/London")
DateTime dtNow = new DateTime(DateTimeZone.getDefault());
System.out.println(dtNow);
// After 5 seconds
DateTime dtAfter5Sec = dtNow.plusSeconds(5);
System.out.println(dtAfter5Sec);
}
}
An instantaneous point on the time-line:
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public class Main {
public static void main(String[] args) {
DateTime now = new DateTime(DateTimeZone.UTC);
System.out.println(now);
// After 5 seconds
DateTime after5Sec = now.plusSeconds(5);
System.out.println(after5Sec);
}
}
Legacy API:
The java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the milliseconds from the Epoch of January 1, 1970. When you print an object of java.util.Date, its toString method returns the date-time calculated from this milliseconds value. Since java.util.Date does not have timezone information, it applies the timezone of your JVM and displays the same. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFomrat and obtain the formatted string from it.
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());
calendar.add(Calendar.SECOND, 5);// -5 if you want to subtract
System.out.println(calendar.getTime());
}
}
java.time.Instant as the bridge between the legacy and the modern API:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
Instant instant = date.toInstant();
// Now you can convert instant to other types of java.time e.g.
ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Dubai"));
System.out.println(zdt);
}
}
For whatsoever purpose, if you want to convert instant to an object of java.util.Date:
Date dateTime = Date.from(instant);

Easiest solution:
if it is the current date use:
Long seconds= 10; //update in seconds
//seconds*1000 to convert second to millisecond
Date dateAfterUpdation = new Date(System.currentTimeMillis() - (seconds*1000) );
For a specific Date:
Long seconds= 10; //update in seconds
//seconds*1000 to convert second to millisecond
Date dateAfterUpdation = new Date(oldDate.getTime() - (seconds*1000) );
Similarly, you can add or subtract any amount of time by this trick.

FYI, here is some example code using Joda-Time 2.3. The bundled java.util.Date and .Calendar classes are notoriously troublesome, and should be avoided.
Unlike a java.util.Date, a Joda-Time DateTime object has an assigned time zone.
When specifying time zones, use a proper time zone name. Avoid the three or four letter codes as they are neither standardized nor unique.
java.util.Date date = new java.util.Date(); // Has no time zone. Misnamed, as it contains both a date and a time portions.
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Karachi" );
DateTime dateTime = new DateTime( date, timeZone );
DateTime dateTimeUtc = dateTime.withZone( DateTimeZone.UTC );
DateTime fiveSecondsAgo = dateTime.minusSeconds( 5 );
java.util.Date date2 = fiveSecondsAgo.toDate();
Dump to console…
System.out.println( "date: " + date );
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "fiveSecondsAgo: " + fiveSecondsAgo );
System.out.println( "date2: " + date2 );
When run…
date: Thu Apr 17 14:44:01 PDT 2014
dateTime: 2014-04-18T02:44:01.773+05:00
dateTimeUtc: 2014-04-17T21:44:01.773Z
fiveSecondsAgo: 2014-04-18T02:43:56.773+05:00
date2: Thu Apr 17 14:43:56 PDT 2014

An easy way is to use apache DateUtils.
import org.apache.commons.lang.time.DateUtils;
DateUtils.addSeconds(now, 5); // Add 5 seconds.
DateUtils.addSeconds(now, -5); // Subtracting 5 seconds
You can also add/subtract minutes, hours, and so on...

Related

Java Convert String and Long to DateTime

I would like to generate a DateTime variable from two different variables (get the date from myLongDateAndTime and time from myStringTime, how can I do that?
String myStringTime="12:30:10"; // Come from DB
long myLongDateAndTime= 1628197200000 // Come from another DB stores date and times in timestamp format of Thu Aug 05 2021 17:00:00 GMT-0400
DateTime myDateTime=??? // should get Thu Aug 05 2021 12:30:10
java.time
Quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
import java.time.Instant;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
String myStringTime = "12:30:10";
long myLongDateAndTime = 1628197200000L;
LocalTime time = LocalTime.parse(myStringTime);
System.out.println(time);
Instant instant = Instant.ofEpochMilli(myLongDateAndTime);
System.out.println(instant);
OffsetDateTime odt = instant.atOffset(ZoneOffset.of("-04:00"));
System.out.println(odt);
odt = odt.with(time);
System.out.println(odt);
}
}
Output:
12:30:10
2021-08-05T21:00:00Z
2021-08-05T17:00-04:00
2021-08-05T12:30:10-04:00
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
Just for the sake of completeness
Just for the sake of completeness, given below is the solution using the Joda Date-Time API:
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;
public class Main {
public static void main(String[] args) {
String myStringTime = "12:30:10";
long myLongDateAndTime = 1628197200000L;
LocalTime time = LocalTime.parse(myStringTime);
System.out.println(time);
DateTime dateTime = new DateTime(Long.valueOf(myLongDateAndTime), DateTimeZone.forOffsetHours(-4));
System.out.println(dateTime);
dateTime = dateTime.withTime(time);
System.out.println(dateTime);
}
}
Output:
12:30:10.000
2021-08-05T17:00:00.000-04:00
2021-08-05T12:30:10.000-04:00
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
You are combining two dates, so what you need to do is:
create a joda DateTime from the long
format that DateTime to a string with only the date part
combine with date string and time string in a single string
parse the new string
and here is how you can do that:
public DateTime combineDates(long myLongDateAndTime, String myStringTime) {
// 1 - create DateTime from the long
DateTime dateFromLong = new DateTime(myLongDateAndTime);
// 2 - Format dateFromLong as date string
DateTimeFormatter dtfDate = DateTimeFormat.forPattern("dd/MM/yyyy");
String dateString = dtfDate.print(dateFromLong);
// 3 - Concatenate date part and time part in a new string
String completeDate = dateString + " " + myStringTime;
// 4 - Parse the new string in to a DateTime
DateTimeFormatter dtfDateTime =
DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
return dtfDateTime.parseDateTime(completeDate);
}
This is only a possible solution. There are many other ways to do the same, for example without using a string concatenation, but only dates operations, but this way is quite clear and readable, so I don't investigate additional possible solutions.
One possible solution:
public class TestSample {
public static void main(String[] args) {
String myStringTime="12:30:10";
Long myLongDateAndTime= 1628197200000L;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.ENGLISH);
LocalTime time = LocalTime.parse(myStringTime, formatter);
LocalDate date = Instant.ofEpochMilli(myLongDateAndTime).atZone(ZoneId.of("UTC")).toLocalDate();
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
LocalDateTime dtTime = LocalDateTime.parse(date.toString()+" "+time.toString(), formatter1);
System.out.println(dtTime.toString());
}
}

Convert integer date time into real date time problem? JAVA [duplicate]

This question already has answers here:
Convert Json date to java date
(3 answers)
How can I convert Json Date to Java Date
(6 answers)
Closed 2 years ago.
so I have this problem converting Integer DateTime format to normal DateTime format in Java.
I have this this variable int DateTime, for example it is : "/Date(1484956800000)/" . And i am trying to convert it to normal date time and show it to the screen ...
I tried like this..
String dateAsText = new SimpleDateFormat("MM-dd HH:mm")
.format(new Date(Integer.parseInt(deals.getDate_time()) * 1000L));
// setting my textView with the string dateAsText
holder.Time.setText(dateAsText);
I suggest you stop using the outdated and error-prone java.util date-time API and SimpleDateFormat. Switch to the modern java.time date-time API and the corresponding formatting API (java.time.format). Learn more about the modern date-time API from Trail: Date Time.
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Obtain an instance of Instant using milliseconds from the epoch of
// 1970-01-01T00:00:00Z
Instant instant = Instant.ofEpochMilli(1484956800000L);
System.out.println(instant);
// Specify the time-zone
ZoneId myTimeZone = ZoneId.of("Europe/London");
// Obtain ZonedDateTime out of Instant
ZonedDateTime zdt = instant.atZone(myTimeZone);
// Obtain LocalDateTime out of ZonedDateTime
// Note that LocalDateTime throws away the important information of time-zone
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println(ldt);
// Custom format
String dateAsText = ldt.format(DateTimeFormatter.ofPattern("MM-dd HH:mm"));
System.out.println(dateAsText);
}
}
Output:
2017-01-21T00:00:00Z
2017-01-21T00:00
01-21 00:00
If you still want to use the poorly designed legacy java.util.Date, you can do it as follows:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date date = new Date(1484956800000L);
System.out.println(date);
// Custom format
String dateAsText = new SimpleDateFormat("MM-dd HH:mm").format(date);
System.out.println(dateAsText);
}
}
Output:
Sat Jan 21 00:00:00 GMT 2017
01-21 00:00

Java Date + Calendar giving different results than expected

I have the following code:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CalendarTest {
public static void main(String[] args) {
try {
Calendar calendar = Calendar.getInstance();
Date _date = new SimpleDateFormat("ddMMyyyy").parse("13102014");
Date _time = new SimpleDateFormat("hhmmss").parse("201100");
calendar.setTimeInMillis(_date.getTime() + _time.getTime());
System.out.println(calendar.getTime()); // NOK 1 hour less
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
Why does it produce:
Mon Oct 13 19:11:00 CEST 2014
Instead of:
Mon Oct 13 20:11:00 CEST 2014
UTC versus DST
Because java.util.Date works in UTC. But its toString method confusingly applies your JVM’s current default time zone when generating a String representation of the date-time value.
I imagine your JVM’s current default time zone is in Daylight Saving Time (DST), thus the hour adjustment.
24-Hour Time
Also, your hour-of-day code should be HH for 24-hour time, not hh for 12-hour time.
When you parse only the time on a separate line from the date, it treats it as though that time occurs on Jan 1st 1970. Which is in the winter when you are on standard time. So when you combine the two together you get a value that's in standard time, one hour behind the current clock-on-the-wall time which is in Daylight time.
I would say that it's possible to produce the desired output with a simple change. No JODA or Java 8 needed. I don't understand why you wrote it the way you did.
package cruft;
/**
* CalendarTest description here
* #author Michael
* #link https://stackoverflow.com/questions/26348140/java-date-calendar-giving-different-results-as-expected
* #since 10/13/2014 4:16 PM
*/
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CalendarTest {
public static void main(String[] args) {
try {
Calendar calendar = Calendar.getInstance();
Date _date = new SimpleDateFormat("ddMMyyyy hhmmss").parse("13102014 201100");
calendar.setTimeInMillis(_date.getTime());
System.out.println(calendar.getTime());
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
Here's the output I get:
"C:\Program Files\Java\jdk1.7.0_45\bin\java" -Didea.launcher.port=7536 "
Mon Oct 13 20:11:00 EDT 2014
Process finished with exit code 0
Joda-Time
The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use a competent date-time library instead. In Java that means either:
Joda-TimeThe venerable library used by many people for many years as a replacement for j.u.Date/Calendar.
java.timeBundled with Java 8, inspired by Joda-Time, defined by JSR-310, described in The Tutorial)
In Joda-Time, a DateTime object knows its own assigned time zone (unlike j.u.Date).
That string format in your Question is annoyingly bad. If possible, replace with ISO 8601 standard strings. The standard strings are much more readable and intuitive. Furthermore, both Joda-Time and java.time parse and generate standard strings by default.
Example code using Joda-Time 2.5. We do not know your time zone, so I am arbitrarily choosing Berlin. I assume your input string represents a moment in that time zone, though your Question is ambiguous.
Parse input string.
String input = "13102014201100";
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Berlin" );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "ddMMyyyyHHmmss" );
DateTimeFormatter formatterBerlin = formatter.withZone( timeZone );
DateTime dateTimeBerlin = formatterBerlin.parseDateTime( input );
Adjust to another time zone. In this case, UTC.
DateTime dateTimeUtc = dateTimeBerlin.withZone( DateTimeZone.UTC );
Dump to console.
System.out.println( "input: " + input );
System.out.println( "dateTimeBerlin: " + dateTimeBerlin );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
When run.
input: 13102014201100
dateTimeBerlin: 2014-10-13T20:11:00.000+02:00
dateTimeUtc: 2014-10-13T18:11:00.000Z

Millis for a given date are wrong using Date.parse(dateString)

I have a date string of 1/1/1970 8:00 AM
The correct millis should be 8 hours * 60 minutes per hour * 60000 milliseconds per minute = 28800000
However, using Date.parse(dateString) returns 50400000
What am I not understanding?
Edit
I originally tried using date.getTime();
Here's my original code:
SimpleDateFormat dateFmt = new SimpleDateFormat("MM/dd/yyyy h:mm a");
dateFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
StringBuilder sb = new StringBuilder();
sb.append(month).append("/");
sb.append(day).append("/");
sb.append(year).append(" ");
sb.append(pad(hour)).append(":");
sb.append(pad(minute)).append(" ");;
sb.append(ampm);
Date date = new Date();
date = dateFmt.parse(sb.toString());
date.getTime()
This is almost certainly the problem:
If no time zone is specified, the local time zone is assumed.
My guess is that you're in a time zone which was at UTC-6 at the Unix epoch, so 8am local time was 2pm UTC.
Then there's the more fundamental problem of you using deprecated methods when there are better alternative (SimpleDateFormat, which allows you to set the time zone) available. Methods are deprecated for a reason. You shouldn't just use deprecated methods regardless, otherwise you'll keep running into things like this.
In fact, you'd be better off using Joda Time if you possibly can - but at least stay away from the deprecated methods in Date.
Sample code:
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy h:mm aa", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
long millis = format.parse(text).getTime();
You may want to change dd/MM to MM/dd, depending on what format your dates are going to be in - we can't tell from "01/01". Note the explicit setting of both time zone and locale.
Its because of your local timezone. Use Simple date format with timezone as below to get your desired value against UTC timezone:
DateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
String dateS = "1/1/1970 8:00 AM";
format.setTimeZone(TimeZone.getTimeZone("UTC"));
format.setLenient(true);
Date date = format.parse(dateS);
System.out.println(date.getTime()); //<-- prints 28800000
or more compact:
DateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = format.parse("1/1/1970 8:00 AM");
System.out.println(date.getTime()); //<-- prints 28800000
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
You do not need to form the string: You can use LocalDateTime#of to create an instance of LocalDateTime which can be converted into an Instant in order to get the number of milliseconds from the Unix epoch.
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
int year = 1970, month = 1, dayOfMonth = 1, hour = 8, minute = 0;
LocalDateTime ldt = LocalDateTime.of(year, month, dayOfMonth, hour, minute);
Instant instant = ldt.toInstant(ZoneOffset.UTC);
System.out.println(instant.toEpochMilli());
}
}
Output:
28800000
ONLINE DEMO
If you already have a date-time string in the given format:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/u h:m a", Locale.ENGLISH);
String strDateTime = "1/1/1970 8:00 AM";
LocalDateTime ldt = LocalDateTime.parse(strDateTime, dtf);
Instant instant = ldt.toInstant(ZoneOffset.UTC);
System.out.println(instant.toEpochMilli());
}
}
Output:
28800000
ONLINE DEMO
An Instant represents an instantaneous point on the timeline in UTC.
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

how to get a formatted date as milliseconds?

I have a formatted date from sqllite database, to use this in a graph view I need to format it in a long number.
The format is:
2012-07-11 10:55:21
how can I convert it to milliseconds?
You can convert the string into a Date object using this code:-
Date d = DateFormat.parse(String s)
And then convert it into milliseconds by using the inbuilt method
long millisec = d.getTime();
Use date.getTime()
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd, HH:mm:ss");
formatter.setLenient(false);
String oldTime = "2012-07-11 10:55:21";
Date oldDate = formatter.parse(oldTime);
long oldMillis = oldDate.getTime();
try this:
import java.util.*;
public class ConvertDateIntoMilliSecondsExample{
public static void main(String args[]){
//create a Date object
Date date = new Date();
System.out.println("Date is : " + date);
//use getTime() method to retrieve milliseconds
System.out.println("Milliseconds since January 1, 1970, 00:00:00 GMT : "
+ date.getTime());
}
}
java.time
Solution using java.time, the modern date-time API*:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(toMillis("2012-07-11 10:55:21"));
}
public static long toMillis(String strDateTime) {
// Replace the parameter, ZoneId.systemDefault() which returns JVM's default
// timezone, as applicable e.g. to ZoneId.of("America/New_York")
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u-M-d H:m:s", Locale.ENGLISH)
.withZone(ZoneId.systemDefault());
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
Instant instant = zdt.toInstant();
return instant.toEpochMilli();
}
}
Output:
1342000521000
Learn more about the the modern date-time API* from Trail: Date Time.
*For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Categories