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);
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.
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;
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());
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….
Kotlin
val dateString = "17-09-2021"
val formatter = SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH)
val date = formatter.parse(dateString) as Date
Log.i("i","Today is " + date.time)
You'll get something that resembles 1616668471659
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
Related
I try convert UTC time to local time , minute work well but hour always have 1hour later, for example if UTC time is 04:55 , my phone clock is 9:25 but my code generate 8:25
String dateStr = "04:55";
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
date = df.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
df.setTimeZone(TimeZone.getDefault());
String formattedDate = df.format(date);
time.setText(String.valueOf(formattedDate));
No DST in Iran in 1970
The time zone for Iran, Asia/Tehran, observes Daylight Saving Time (DST) in the summer of 2018 but did not do so back in 1970.
In summer of 2018, Iran is four and a half hours ahead of UTC rather than three and a half. So adjusting from 4:55 in UTC should result in 9:25 on a summer day, not 8:25.
System.out.println(
OffsetDateTime.of(
LocalDate.of( 2018 , Month.JUNE , 1 ) ,
LocalTime.parse( "04:55" ) ,
ZoneOffset.UTC
)
.atZoneSameInstant(
ZoneId.of( "Asia/Tehran" )
)
);
2018-06-01T09:25+04:30[Asia/Tehran]
But I suspect your code is defaulting to the epoch reference date of first moment of 1970 in UTC when parsing your string, 1970-01-01T00:00:00Z, because you are abusing that class in trying to parse a time-of-day without specifying a date.
In 1970, Iran did not observe Daylight Saving Time (DST). So the offset was three and a half hours ahead of UTC in summer of 1970 versus four and a half hours ahead of UTC in summer of 2018.
System.out.println(
OffsetDateTime.of(
LocalDate.EPOCH ,
LocalTime.parse( "04:55" ) ,
ZoneOffset.UTC
)
.atZoneSameInstant(
ZoneId.of( "Asia/Tehran" )
)
);
1970-01-01T08:25+03:30[Asia/Tehran]
Wrong classes
You are using the wrong classes.
You want to represent a time-of-day value. So you should be using a time-of-day class. But you are using a date-with-time-of-day class, java.util.Date.
You are using troublesome badly-designed date-time classes, java.util.Date & java.text.SimpleDateFormat. These were supplanted years ago by the java.time classes. Avoid the legacy classes entirely. Use only the classes found in the java.time package.
Time-of-day
Parse a time-of-day string.
LocalTime.parse( "04:55" )
Get the current time-of-day.
LocalTime.now() // Capture the current time of day per the JVM’s current default time zone.
Better to make explicit your intention to use the JVM’s current default time zone.
LocalTime.now(
ZoneId.systemDefault() // Capture the current time of day by explicitly asking for the JVM’s current default time zone.
)
Or specify a particular time zone.
LocalTime.now(
ZoneId.of( "Asia/Kabul" ) // Capture the current time-of-day as seen in the wall-clock time used by the people of a particular region (a time zone).
)
9:25
Get the current time-of-day in UTC.
LocalTime.now(
ZoneOffset.UTC
)
04:55
LocalTime
If you have an input string such as "04:55", parse as a LocalTime object. This class represents a time-of-day without a date and without a time zone.
String input = "04:55" ;
LocalTime lt = LocalTime.parse( input ) ;
Terminology
I try convert UTC time to local time
Your phrase “local time” has a specific meaning in date-time handling. Unfortunately that meaning is the opposite of your intention. The word “local” as seen in the *java.time.Local…” classes mean any locality or all localities rather than any one particular locality.
So a LocalTime object has no real meaning until attached to a date and placed in the context of a time zone (or offset-from-UTC).
Time zones
if UTC time is 04:55 , my phone clock is 9:25
That means your JVM’s current default time zone is using an offset-from-UTC four and a half hours ahead of UTC, +04:30. According to this list of time zones as managed by the IANA, there are only one time zone currently using that offset: Asia/Kabul.
To represent the current moment fully, you need a date and a time-of-day and a zone/offset. To capture the current moment, use Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ; // Capture the current moment in UTC.
To see that same moment in your time zone, apply a ZoneId to get a ZonedDateTime.
ZoneId zKabul = ZoneId.of( "Asia/Kabul" ) ;
ZonedDateTime zdt = instant.atZone( zKabul ) ;
If you really want only the time-of-day portion of that value, extract a LocalTime. This might be useful for rendering in a user-interface, but is not likely useful in your business logic.
LocalTime lt = zdt.toLocalTime() ; // Extract just the time-of-day as seen in the wall-clock time used by the people of this region (this time zone).
As a shortcut, you could call LocalTime.now:
LocalTime lt = LocalTime.now( zKabul ) ;
Iran time
Later in your comments you explain your intended time zone is Asia/Tehran, time in Iran. Currently, Iran observes Daylight Saving Time (DST), which may be the source of your confusion. While standard offset if +03:30 (three and half hours ahead of UTC), between March 22 and September 22 the offset is +04:30, one more hour further ahead of UTC.
This is exactly why you should specify your desired/expected time zone. For casual use, you can use the JVM’s current default time zone. But know that default can change at any moment during runtime. And the default may not be what you intend. For critical usage, always confirm with the user their intended time zone.
Let's build up a date-time for June 1st with your example time 4:55 in UTC. We can use the constant ZoneOffset.UTC. When using merely an offset-from-UTC (an offset of zero in this case), use OffsetDateTime. An offset-from-UTC is merely a number of hours and minutes, nothing more, nothing less. In contrast, a time zone is a history of past, present, and future changes to the offset used by the people of a specific region.
LocalTime lt = LocalTime.parse( "04:55" ) ;
LocalDate ld = LocalDate.of( 2018 , Month.JUNE , 1 ) ;
OffsetDateTime odt = OffsetDateTime.of( ld , lt , ZoneOffset.UTC ) ;
odt.toString(): 2018-06-01T04:55Z
Adjust into the zone Asia/Tehran by applying a ZoneId to get a ZonedDateTime. Same moment, same point on the timeline, but a different wall-clock time.
ZoneId zTehran = ZoneId.of( "Asia/Tehran" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( zTehran );
zdt.toString(): 2018-06-01T09:25+04:30[Asia/Tehran]
Note the time-of-day in summer shows as 9 hour, not 8.
Try the same code with month of January, when DST is not in effect.
LocalTime lt = LocalTime.parse( "04:55" );
LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 1 );
OffsetDateTime odt = OffsetDateTime.of( ld , lt , ZoneOffset.UTC );
ZoneId zTehran = ZoneId.of( "Asia/Tehran" );
ZonedDateTime zdt = odt.atZoneSameInstant( zTehran );
zdt.toString(): 2018-01-01T08:25+03:30[Asia/Tehran]
Now we see an hour of 8.
Zone names
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-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" ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
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, and later
Built-in.
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
Much 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….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
df.setTimeZone(TimeZone.getDefault());
to
df.setTimeZone(TimeZone.getTimeZone("GMT+4:30"));
working code
String dateStr = "04:55";
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
date = df.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
df.setTimeZone(TimeZone.getTimeZone("GMT+4:30"));
String formattedDate = df.format(date);
System.out.println(formattedDate);
//time.setText(String.valueOf(formattedDate));
}
output i got 9:25
Try this method
public static String convertUTCtoLocalTimeZone(String date, String date_formate) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(date_formate,Locale.getDefault());
Date myDate = null;
try {
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
myDate = simpleDateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return new SimpleDateFormat(date_formate, Locale.getDefault()).format(myDate); // Note: Use new DateFormat
}
Try below method:
private String convertDateToUserTimeZone(String serverDate) {
String ourdate;
try {
SimpleDateFormat serverFormatter = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.UK);
serverFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = serverFormatter.parse(serverDate);
TimeZone timeZone = TimeZone.getTimeZone("Asia/Kolkata");
// SimpleDateFormat dateFormatter = new SimpleDateFormat(serverdateFormat, Locale.UK); //this format changeable
serverFormatter.setTimeZone(timeZone);
ourdate = serverFormatter.format(value);
//Log.d("OurDate", OurDate);
} catch (Exception e) {
ourdate = "00-00-0000 00:00";
}
return ourdate;
}
All Android supported Timezone Android Timezone
I would suggest JodaTime Lib for Date time.Its have rich useful features.
String DOB = new DateTime(Long.parseLong(dob) * 1000, DateTimeZone.UTC ).toString();
// Current
// YYYY-MM-DD
// DOB = "1994-05-10T00:00.000Z"
// Required
// DD-MM-YYYY
// DOB = "10-05-1994"
I want to remove the hh:mm:ss and format the date using Joda-Time DateTimeFormatter.
try this:
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS zzz");
// pass your DOB String
DateTime jodatime = dtf.parseDateTime(DOB);
// Format for output
DateTimeFormatter dtfOut = DateTimeFormat.forPattern("dd-MM-yyyy");
// Print the date
System.out.println(dtfOut.print(jodatime));
tl;dr
Use java.time classes.
Instant.ofEpochSecond( 1_485_748_890L )
.atZone( ZoneId.of( "America/Montreal" ) )
.toLocalDate()
.format(
DateTimeFormatter.ofPattern ( "dd-MM-uuuu" )
.withLocale ( Locale.UK )
)
29-01-2017
Joda-Time
If you want a date-only value without a time-of-day, you should be using the org.joda.time.LocalDate class.
FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. Much of java.time is back-ported to Java 6, Java 7, and Android (see below).
java.time
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate birthdate = LocalDate.of( 1994 , 5 , 10 );
If your input is a count of whole seconds since the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00Z), convert to an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.ofEpochSecond( 1_485_748_890L );
To view this moment through the lens of a particular region’s wall-clock time, assign a time zone (ZoneId) to get a ZonedDateTime.
A time zone is crucial in determining a date. 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.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-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" );
ZonedDateTime zdt = instant.atZone( z );
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = zdt.toLocalDate();
To generate a String representing the value of your object, call toString for a string in standard ISO 8601 format, YYYY-MM-DD.
ld.toString(): 2017-01-29
For other formats, use the DateTimeFormatter class. You can specify a formatting pattern, or let the class automatically localize.
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "dd-MM-uuuu" ).withLocale ( Locale.UK );
String output = ld.format ( f );
instant.toString(): 2017-01-30T04:01:30Z
zdt.toString(): 2017-01-29T23:01:30-05:00[America/Montreal]
ld.toString(): 2017-01-29
output: 29-01-2017
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.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
try this :
String textDate ="1994-05-10T00:00.000Z"; //Date to convert
DateTimeFormatter DATE_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ"); //Default format
SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()); //Needed format
DateTime dateTime = new DateTime(DATE_FORMAT.parseDateTime(textDate), DateTimeZone.forID(current.getID()));
Calendar cal=dateTime.toCalendar(Locale.getDefault());
String formatted = SIMPLE_DATE_FORMAT.format(cal.getTime()); //Final Required date
I want to convert milliSeconds in long format to Gregorian Calendar.
By searching in the web, i use the code below:
public static String getStringDate(int julianDate){
GregorianCalendar gCal = new GregorianCalendar();
Time gTime = new Time();
gTime.setJulianDay(julianDate);
gCal.setTimeInMillis(gTime.toMillis(false));
String gString = Utils.getdf().format(gCal.getTime());
return gString;
}
public static SimpleDateFormat getdf(){
return new SimpleDateFormat("yyyy-MM-dd, HH:MM",Locale.US);
}
Yes, the code works but i find that only the date and the hour are correct but there are errors on minutes. Say if the thing happens on 2014-11-06, 14:00, it will give me 2014-11-06, 14:11. I want to know are there any solutions to modify it or it is not recommended to convert time into Gregorian Calendar. Many thanks!
The problem actually is very simple,
modify SimpleDateFormat("yyyy-MM-dd, HH:MM",Locale.US) with
SimpleDateFormat("yyyy-MM-dd, HH:mm",Locale.getDefault());
will solve the problem
tl;dr
Instant.ofEpochMilli( millis ) // Convert count-from-epoch into a `Instant` object for a moment in UTC.
.atZone( ZoneId.of( "Pacific/Auckland" ) ) // Adjust from UTC to a particular time zone. Same moment, different wall-clock time. Renders a `ZonedDateTime` object.
.format( // Generate a String in a particular format to represent the value of our `ZonedDateTime` object.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd, HH:mm" )
)
java.time
The modern approach uses the java.time classes instead of those troublesome legacy classes.
Convert your count of milliseconds since the epoch reference of first moment of 1970 (1970-01-01T00:00Z) to a Instant object. Be aware that Instant is capable of finer granularity of nanoseconds.
Instant instant = Instant.ofEpochMilli( millis ) ;
That moment is in UTC. To adjust into another time zone, apply a ZoneId to get a ZonedDateTime.
A time zone is crucial in determining a date. 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, 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 3-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( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Generate a string in your desired format using a DateTimeFormatter object.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd, HH:mm" , Locale.US ) ;
String output = zdt.format( f ) ;
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.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
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
Much 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, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
I want to get the current time on the device in the format: 2013-10-17 15:45:01 ?
The server sends me the date of an object in the format above as a string. Now i want to get the phones current time and then check if there is a difference of say more than 5 minutes?
So A: How can i get the devices current time in this fomat: 2013-10-17 15:45:01
B how can I work out the difference between the two.
You can use SimpleDateFormat to specify the pattern you want:
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new java.util.Date())
However, if you just want to know whether the time difference is within a certain threshold, you should probably just compare long values. If your threshold is 5 minutes, then this is 5 * 60 * 1000 milliseconds so you can use the same SimpleDateFormat by calling it's parse method and check the long values.
Example:
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2013-10-13 14:54:03").getTime()
Date currentDate = new Date(); will initialize a new date with the current time. In addition, convert the server provided time and take the difference.
String objectCreatedDateString = "2013-10-17 15:45:01";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date objectCreatedDate = null;
Date currentDate = new Date();
try
{objectCreatedDate = format.parse(objectCreatedDateString);}
catch (ParseException e)
{Log.e(TAG, e.getMessage());}
int timeDifferential;
if (objectCreatedDate != null)
timeDifferential = objectCreatedDate.getMinutes() - currentDate.getMinutes();
tl;dr
Duration.between( // Calculate time elapsed between two moments.
LocalDateTime // Represent a date with time-of-day but lacking the context of a time zone or offset-from-UTC.
.parse( "2013-10-17 15:45:01".replace( " " , "T" ) )
.atOffset( ZoneOffset.UTC ) // Returns an `OffsetDateTime` object.
.toInstant() , // Returns an `Instant` object.
Instant.now() // Capture the current moment as seen in UTC.
)
.toMinutes()
> 5
java.time
The other Answers are outdated, using terrible classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
Parse your incoming string.
String input = "2013-10-17 15:45:01" ;
Modify the input to comply with ISO 8601. I suggest you educate the publisher of your data about the ISO 8601 standard.
String inoutModified = input.replace( " " , "T" ) ;
Parse as a LocalDateTime because this input lacks an indicator of the intended offset or time zone.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
I assume that input was intended to represent a moment as seen in UTC, with an offset of zero hours minutes seconds. If so, educate the publisher of your data about appending a Z on the end to so indicate, per ISO 8601.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
Extract an object of the simpler class, Instant. This class is always in UTC.
Instant then = odt.toInstant() ;
Get current moment as seen in UTC.
Instant now = Instant.now() ;
Calculate the difference.
Duration d = Duration.between( then , now ) ;
Get duration as total whole minutes.
long minutes = d.toMinutes() ;
Test.
if ( minutes > 5 ) { … }
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
Use SimpleDateFromat Class
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dateFormatter.format(date);
Also check this documentation
If you can ask the server to send you an RFC3339 compliant date/time string, then Here is a simple answer to both of your questions:
public String getClientTime() {
Time clientTime = new Time().setToNow();
return clientTime.format("%Y-%m-%d %H:%M:%S");
}
public int diffClientAndServerTime(String svrTimeStr) {
Time svrTime = new Time();
svrTime.parse3339(svrTimeStr);
Time clientTime = new Time();
clientTime.setToNow();
return svrTime.compare( svrTime, clientTime);
}
I have the below code
public Long getEpochTime(String dateToGetItsEpoch) throws ParseException
{
TimeZone timeZone = TimeZone.getTimeZone("UTC");
final String REQUEST_DATE_FORMAT = "dd/MM/yyyy h:m";
DateFormat format = new SimpleDateFormat(REQUEST_DATE_FORMAT);
Date localDate = format.parse(dateToGetItsEpoch);
Calendar cal = Calendar.getInstance(timeZone);
cal.setTime(localDate);
format.setTimeZone(timeZone);
final String utcTime = format.format(cal.getTime());
Date d = cal.getTime();
return d.getTime();
}
If I change the locale of my device to whatever, I always get the UTC time as the return value. Which is correct, however I want to know how is this happening ? How does the device know Which timezone is the date I am giving to it so that it calculates accordingly ?
A Date doesn't have a time zone at all. A SimpleDateFormat does as a default for parsing and formatting; a Calendar does too; a Date doesn't.
Given this sequence of operations:
TimeZone timeZone = TimeZone.getTimeZone("UTC");
DateFormat format = new SimpleDateFormat(REQUEST_DATE_FORMAT);
Date localDate = format.parse(dateToGetItsEpoch);
Calendar cal = Calendar.getInstance(timeZone);
cal.setTime(localDate);
format.setTimeZone(timeZone);
final String utcTime = format.format(cal.getTime());
... you're initially parsing the string using the default time zone of the device, then you're formatting it in UTC. Note that the Calendar part is irrelevant here - you'd get the same result with:
TimeZone timeZone = TimeZone.getTimeZone("UTC");
DateFormat format = new SimpleDateFormat(REQUEST_DATE_FORMAT);
Date date = format.parse(dateToGetItsEpoch);
format.setTimeZone(timeZone);
final String utcTime = format.format(date);
I would personally recommend using Joda Time where possible for date/time work in Java, mind you. It's a much cleaner API than Calendar/Date.
java.time
The Answer by Jon Skeet is correct. Here is some code updated to use the modern java.time classes that have supplanted the troublesome legacy date-time classes.
Formatting pattern
Define a formatting pattern to match your inputs.
By the way, yours is a poor choice of formats. Instead I recommend using the standard ISO 8601 formats designed for exchanging date-time values as text.
12-hour versus 24-hour clock
Your input data or formatting pattern has a flaw. You used lowercase h which means one or two digits for an hour in the 12-hour clock (rather than 24-hour clock, which is uppercase H or HH). So your input makes no sense unless you add some indicator of AM or PM. I will assume you mistakenly omitted this from your Question's code.
Locale locale = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu h:m a" ).withLocale( locale ) ;
LocalDateTime
Parse such strings as LocalDateTime objects, as they lack an indicator of the intended time zone or offset-from-UTC.
String input = "23/01/2020 4:5 PM" ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
ldt.toString(): 2020-01-23T16:05
Moment
The LocalDateTime object we obtained above does not represent a moment, is not a point on the timeline. We have a time of around 4 PM on the 23rd. But we cannot know if this was meant to be 4 PM in Tokyo, Toulouse, or Toledo — all very different moments several hours apart.
To determine a moment, we must know for certain the intended time zone. Then apply that zone as a ZoneId to get a ZonedDateTime. Then we have arrived at a moment.
Locale is not a time zone
locale of my device to whatever
A Locale has nothing to with time zone. A Locale is used for localizing generated text representing a date-time object.
To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine:
The human language for translation of name of day, name of month, and such.
The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Example:
Locale l = Locale.CANADA_FRENCH ; // Or Locale.US, Locale.JAPAN, etc.
DateTimeFormatter f =
DateTimeFormatter
.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( l )
;
String output = myZonedDateTime.format( f );
You could have an engineer from Québec who uses the Locale.CANADA_FRENCH for human language and cultural norms, but while visiting in Japan uses Asia/Tokyo time zone for scheduling appointments.
ZonedDateTime
Back to your LocalDateTime object. If you are certain it was meant to represent a moment as seen in the wall-clock time in Tunisia, then apply a time zone of Africa/Tunis.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
You asked:
How does the device know Which timezone is the date I am giving to it so that it calculates accordingly ?
You were using terrible date-time classes that failed to account for the concept of a date-time lacking an indicator of time zone or offset-from-UTC. So technically, your code is a mess, a hack, unavoidable in those days before Joda-Time and its successor, java.time.
I suggest spending no effort on trying to understand that behavior of Date & Calendar. Just move on to using java.time, the industry-leading date-time handling framework.