Date difference in different timezones in java - java

I am pragmatically building a nested JSON from a table. Json looks something like this:
{"date":"03-16-2018 06:57:02",
"details":
[
{
"motorstate":0,
"startTime":"03-16-2018 20:41:57",
},
{
"motorstate":0,
"startTime":"03-16-2018 06:57:02",
}
]
},
{"date":"03-15-2018 08:08:48",
"details":
[
{
"motorstate":0,
"startTime":"03-16-2018 03:53:30",
}
]
}
If you look into the above example, the second record:
{"date":"03-15-2018 08:08:48",
"details":
[
{
"motorstate":0,
"startTime":"03-16-2018 03:53:30",
}
]
}
The dates are mismatching. This is because the date shown here is in IST but actually stored in UTC in my Google Datastore. In UTC, its still 03-15-2018 and not 03-16-2018.
My question is how can we perform a date difference in different timezones other than UTC in Java? The Date.getTime() method always give the difference in UTC and not in local Timezone.

tl;dr
Date difference in different timezones in java
Period.between(
LocalDateTime.parse(
"03-15-2018 08:08:48" ,
DateTimeFormatter.ofPattern( “MM-dd-uuuu HH:mm:ss” )
)
.atZone( ZoneId.of( ”Asia/Kolkata" ) )
.toLocalDate()
,
LocalDate.now( ZoneId.of( ”Asia/Kolkata" ) )
)
Details
The modern approach uses the java.time classes rather than the troublesome old me old legacy date-time classes such as Date and Calendar.
Tip: Avoid custom formatting patterns when serializing date-time values to text. Use standard ISO 8601 formats only.
Tip: when exchanging date-time values as text, always include an indicator of the offset-from-UTC and the time zone name.
First, parse your input strings as LocalDateTime because they lack any indication of offset or zone.
Define a formatting pattern to match input.
DateTimeFormatter f = DateTimeFormatter.ofPattern( “MM-dd-uuuu HH:mm:ss” ) ;
Parse.
String input = "03-15-2018 08:08:48" ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
You claim to know that these inputs were intended to represent a moment in India time. Apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( ”Asia/Kolkata" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
To get the date-only value, extract a LocalDate.
LocalDate ld = zdt.toLocalDate() ;
To represent the delta between dates as a number of years, months, and days unattached to the timeline, use Period.
Period p = Period.between( ldt , LocalDate.now( z ) ) ;
For a count of total days.
long days = ChronoUnit.DAYS.between( start , stop ) ;
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, 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.

public String getSummary(String deviceGuid)
{
Query<com.google.cloud.datastore.Entity> query
= Query.newEntityQueryBuilder()
.setKind("sensordata")
.setFilter(PropertyFilter.eq("deviceguid", deviceGuid))
.setOrderBy(OrderBy.desc("startTime"))
.build();
QueryResults<com.google.cloud.datastore.Entity> resultList =
datastore.run(query);
if(!resultList.hasNext())
{
log.warning("No record found..");
return "No record found";
}
com.google.cloud.datastore.Entity e =null;
com.google.cloud.datastore.Entity pe =null;
SensorDataOut sensorDataOut = new SensorDataOut();
SensorSummaryDataOut summary = new SensorSummaryDataOut();
TotalSummaryDataOut totalSummary = new TotalSummaryDataOut();
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("IST"));
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeZone(TimeZone.getTimeZone("IST"));
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
SimpleDateFormat sdf1 = new SimpleDateFormat("MM-dd-yyyy");
//sdf.setTimeZone(TimeZone.getTimeZone("IST"));
long stopTime;
long startTime;
long pStartTime;
long diffTime;
long diffDay;
Date pDateWithoutTime;
Date eDateWithoutTime;
while(resultList.hasNext())
{
e = resultList.next();
startTime = (e.contains("startTime"))?e.getTimestamp("startTime").toSqlTimestamp().getTime():0;
stopTime = (e.contains("stopTime"))?e.getTimestamp("stopTime").toSqlTimestamp().getTime():0;
//log.info("Start Date : " + e.getTimestamp("startTime").toString() + " - " + String.valueOf(startTime));
//log.info("Stop Date : " + e.getTimestamp("stopTime").toString() + " - " + String.valueOf(stopTime));
//log.info("Usage Volume :" + String.valueOf(e.getLong("usageVolume")));
sensorDataOut = new SensorDataOut();
calendar.setTimeInMillis(stopTime);
sensorDataOut.stopTime = sdf.format(calendar.getTime());
calendar.setTimeInMillis(startTime);
sensorDataOut.startTime = sdf.format(calendar.getTime());
sensorDataOut.motorstate = (e.contains("motorstate"))?(int)e.getLong("motorstate"):-1;
sensorDataOut.startVolume = (e.contains("startVolume"))?(int)e.getLong("startVolume"):-1;
sensorDataOut.stopVolume = (e.contains("stopVolume"))?(int)e.getLong("stopVolume"):-1;
sensorDataOut.usageTime = (e.contains("usageTime"))?e.getLong("usageTime"):-1;
sensorDataOut.usageVolume = (e.contains("usageVolume"))?(int)e.getLong("usageVolume"):-1;
if(pe!=null)
{
//Get the date difference in terms of days. If it is same day then add the volume consumed
pStartTime= pe.getTimestamp("startTime").toSqlTimestamp().getTime();
try{
calendar.setTimeInMillis(pStartTime);
pDateWithoutTime = sdf1.parse(sdf1.format(calendar.getTime()));
calendar1.setTimeInMillis(e.getTimestamp("startTime").toSqlTimestamp().getTime());
eDateWithoutTime = sdf1.parse(sdf1.format(calendar1.getTime()));
}
catch(Exception ex){
log.info("Exception while parsing date");
continue;
}
diffTime = Math.abs(pDateWithoutTime.getTime() - eDateWithoutTime.getTime());
diffDay = TimeUnit.DAYS.convert(diffTime, TimeUnit.MILLISECONDS);
//log.info("pDateWithoutTime: " + pDateWithoutTime + ", eDateWithoutTime: " + eDateWithoutTime + ", consumedVolume: "
// + sensorDataOut.usageVolume;
if(diffDay!=0) //If not same day
{
totalSummary.totVolume = totalSummary.totVolume + summary.totVolume;
totalSummary.totDuration = totalSummary.totDuration + summary.totDuration;
totalSummary.details.add(summary);
summary = new SensorSummaryDataOut();
}
}
summary.date = sensorDataOut.startTime;
summary.totVolume = summary.totVolume + sensorDataOut.usageVolume;
summary.totDuration = summary.totDuration + sensorDataOut.usageTime;
summary.details.add(sensorDataOut);
pe = e;
}
if(summary.details.size()>0)
{
totalSummary.totVolume = totalSummary.totVolume + summary.totVolume;
totalSummary.totDuration = totalSummary.totDuration + summary.totDuration;
totalSummary.details.add(summary);
summary = new SensorSummaryDataOut();
}
totalSummary.avgVolume = totalSummary.totVolume/totalSummary.details.size();
totalSummary.deviceguid = deviceGuid;
String json = "";
Gson gson = new Gson();
json = gson.toJson(totalSummary);
return json;
} //End of Function

Below method will return you your UTC time to current Timezone and this worked for me
public static Date getLocalDateObjFromUTC(String date, String time) throws ParseException {
String dateAndTimeInUTC = date + " " + time;
SimpleDateFormat localDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
localDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date dateInLocalTimeZone = localDateFormat.parse(dateAndTimeInUTC);
return dateInLocalTimeZone;
}

Related

How to compare current date with dates from API to display different ImageView if the date from API greater, less, or equal to current date in Kotlin [duplicate]

This question already has answers here:
How do I check if a date is within a certain range?
(17 answers)
Closed 5 years ago.
How do I compare dates in between in Java?
Example:
date1 is 22-02-2010
date2 is 07-04-2010 today
date3 is 25-12-2010
date3 is always greater than date1 and date2 is always today. How do I verify if today's date is in between date1 and date 3?
Date has before and after methods and can be compared to each other as follows:
if(todayDate.after(historyDate) && todayDate.before(futureDate)) {
// In between
}
For an inclusive comparison:
if(!historyDate.after(todayDate) && !futureDate.before(todayDate)) {
/* historyDate <= todayDate <= futureDate */
}
You could also give Joda-Time a go, but note that:
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).
Back-ports are available for Java 6 and 7 as well as Android.
Use compareTo:
date1.compareTo(date2);
Following are most common way of comparing dates (my preference is Approach 1):
Approach 1: Using Date.before(), Date.after() and Date.equals()
if (date1.after(date2)) {
System.out.println("Date1 is after Date2");
}
if (date1.before(date2)) {
System.out.println("Date1 is before Date2");
}
if (date1.equals(date2)) {
System.out.println("Date1 is equal Date2");
}
Approach 2: Date.compareTo()
if (date1.compareTo(date2) > 0) {
System.out.println("Date1 is after Date2");
} else if (date1.compareTo(date2) < 0) {
System.out.println("Date1 is before Date2");
} else {
System.out.println("Date1 is equal to Date2");
}
Approach 3: Calender.before(), Calender.after() and Calender.equals()
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
if (cal1.after(cal2)) {
System.out.println("Date1 is after Date2");
}
if (cal1.before(cal2)) {
System.out.println("Date1 is before Date2");
}
if (cal1.equals(cal2)) {
System.out.println("Date1 is equal Date2");
}
tl;dr
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;
Boolean isBetween =
( ! today.isBefore( localDate1 ) ) // “not-before” is short for “is-equal-to or later-than”.
&&
today.isBefore( localDate3 ) ;
Or, better, if you add the ThreeTen-Extra library to your project.
LocalDateRange.of(
LocalDate.of( … ) ,
LocalDate.of( … )
).contains(
LocalDate.now()
)
Half-open approach, where beginning is inclusive while ending is exclusive.
Bad Choice of Format
By the way, that is a bad choice of format for a text representation of a date or date-time value. Whenever possible, stick with the standard ISO 8601 formats. ISO 8601 formats are unambiguous, understandable across human cultures, and are easy to parse by machine.
For a date-only value, the standard format is YYYY-MM-DD. Note how this format has the benefit of being chronological when sorted alphabetically.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
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.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
DateTimeFormatter
As your input strings are non-standard format, we must define a formatting pattern to match.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" );
Use that to parse the input strings.
LocalDate start = LocalDate.parse( "22-02-2010" , f );
LocalDate stop = LocalDate.parse( "25-12-2010" , f );
In date-time work, usually best to define a span of time by the Half-Open approach where the beginning is inclusive while the ending is exclusive. So we want to know if today is the same or later than the start and also before the stop. A briefer way of saying “is the same or later than the start” is “not before the start”.
Boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ;
See the Answer by gstackoverflow showing the list of comparison methods you can call.
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….
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.
UPDATE: This “Joda-Time” section below is left intact as history. The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
Joda-Time
Other answers are correct with regard to the bundled java.util.Date and java.util.Calendar classes. But those classes are notoriously troublesome. So here's some example code using the Joda-Time 2.3 library.
If you truly want a date without any time portion and no time zone, then use the LocalDate class in Joda-Time. That class provides methods of comparison including compareTo (used with Java Comparators), isBefore, isAfter, and isEqual.
Inputs…
String string1 = "22-02-2010";
String string2 = "07-04-2010";
String string3 = "25-12-2010";
Define a formatter describing the input strings…
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MM-yyyy" );
Use formatter to parse the strings into LocalDate objects…
LocalDate localDate1 = formatter.parseLocalDate( string1 );
LocalDate localDate2 = formatter.parseLocalDate( string2 );
LocalDate localDate3 = formatter.parseLocalDate( string3 );
boolean is1After2 = localDate1.isAfter( localDate2 );
boolean is2Before3 = localDate2.isBefore( localDate3 );
Dump to console…
System.out.println( "Dates: " + localDate1 + " " + localDate2 + " " + localDate3 );
System.out.println( "is1After2 " + is1After2 );
System.out.println( "is2Before3 " + is2Before3 );
When run…
Dates: 2010-02-22 2010-04-07 2010-12-25
is1After2 false
is2Before3 true
So see if the second is between the other two (exclusively, meaning not equal to either endpoint)…
boolean is2Between1And3 = ( ( localDate2.isAfter( localDate1 ) ) && ( localDate2.isBefore( localDate3 ) ) );
Working With Spans Of Time
If you are working with spans of time, I suggest exploring in Joda-Time the classes: Duration, Interval, and Period. Methods such as overlap and contains make comparisons easy.
For text representations, look at the ISO 8601 standard’s:
durationFormat: PnYnMnDTnHnMnSExample: P3Y6M4DT12H30M5S(Means “three years, six months, four days, twelve hours, thirty minutes, and five seconds”)
intervalFormat: start/endExample: 2007-03-01T13:00:00Z/2008-05-11T15:30:00Z
Joda-Time classes can work with strings in both those formats, both as input (parsing) and output (generating strings).
Joda-Time performs comparisons using the Half-Open approach where the beginning of the span is inclusive while the ending is exclusive. This approach is a wise one for handling spans of time. Search StackOverflow for more info.
Compare the two dates:
Date today = new Date();
Date myDate = new Date(today.getYear(),today.getMonth()-1,today.getDay());
System.out.println("My Date is"+myDate);
System.out.println("Today Date is"+today);
if (today.compareTo(myDate)<0)
System.out.println("Today Date is Lesser than my Date");
else if (today.compareTo(myDate)>0)
System.out.println("Today Date is Greater than my date");
else
System.out.println("Both Dates are equal");
Update for Java 8 and later
isAfter()
isBefore()
isEqual()
compareTo()
These methods exists in LocalDate, LocalTime, and LocalDateTime classes.
Those classes are built into Java 8 and later. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
You can use Date.getTime() which:
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Date object.
This means you can compare them just like numbers:
if (date1.getTime() <= date.getTime() && date.getTime() <= date2.getTime()) {
/*
* date is between date1 and date2 (both inclusive)
*/
}
/*
* when date1 = 2015-01-01 and date2 = 2015-01-10 then
* returns true for:
* 2015-01-01
* 2015-01-01 00:00:01
* 2015-01-02
* 2015-01-10
* returns false for:
* 2014-12-31 23:59:59
* 2015-01-10 00:00:01
*
* if one or both dates are exclusive then change <= to <
*/
Try this
public static boolean compareDates(String psDate1, String psDate2) throws ParseException{
SimpleDateFormat dateFormat = new SimpleDateFormat ("dd/MM/yyyy");
Date date1 = dateFormat.parse(psDate1);
Date date2 = dateFormat.parse(psDate2);
if(date2.after(date1)) {
return true;
} else {
return false;
}
}
Use getTime() to get the numeric value of the date, and then compare using the returned values.
This code determine today is in some duration.. based on KOREA locale
Calendar cstart = Calendar.getInstance(Locale.KOREA);
cstart.clear();
cstart.set(startyear, startmonth, startday);
Calendar cend = Calendar.getInstance(Locale.KOREA);
cend.clear();
cend.set(endyear, endmonth, endday);
Calendar c = Calendar.getInstance(Locale.KOREA);
if(c.after(cstart) && c.before(cend)) {
// today is in startyear/startmonth/startday ~ endyear/endmonth/endday
}
This method worked for me:
public static String daysBetween(String day1, String day2) {
String daysBetween = "";
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date1 = myFormat.parse(day1);
Date date2 = myFormat.parse(day2);
long diff = date2.getTime() - date1.getTime();
daysBetween = ""+(TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
e.printStackTrace();
}
return daysBetween;
}

Not able to convert date to epoch time [duplicate]

This question already has answers here:
Convert String to java.util.Date
(4 answers)
Display current time in 12 hour format with AM/PM
(15 answers)
Java - parse date with AM/PM next to seconds (no space)
(5 answers)
Closed 3 years ago.
This is my sample code
String dt = "Oct 24 2019 12:00:00.000 AM UTC";
String dt1="Oct 24 2019 11:59:59.000 PM UTC";
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS
aa zzz");
Date date = df.parse(dt);
Date date1 = df.parse(dt1);
long epoch = date.getTime();
long epoch1 = date1.getTime();
System.out.println(epoch);
System.out.println(epoch1);
Here specifying the AM and PM but its not taking the value for that and throwing the exception as
{"error_code":"INVALID_PARAMETER_VALUE","message":"Time range must have a start time earlier than the end time"}
How to specify AM/PM in the java code.
How can I take yesterday's date and time for today in java code as an input to convert to epoch.
tl;dr
ZonedDateTime
.parse(
"Oct 24 2019 12:00:00.000 AM UTC" ,
DateTimeFormatter.ofPattern( "MMM d uuuu hh:mm:ss.SSS a z" ).withLocale( Locale.US )
)
.toInstant()
.toEpochMilli()
1571875200000
java.time
Two problems:
As commented by Heuberger, you are using incorrect formatting codes.
You are using terrible date-time classes supplanted years ago by the modern java.time classes.
Your inputs, renamed for clarity.
String inputStart = "Oct 24 2019 12:00:00.000 AM UTC";
String inputStop = "Oct 24 2019 11:59:59.000 PM UTC";
Define a formatting pattern to match your inputs.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM d uuuu hh:mm:ss.SSS a z" ).withLocale( Locale.US );
Parse inputs.
ZonedDateTime zdtStart = ZonedDateTime.parse( inputStart , f );
ZonedDateTime zdtStop = ZonedDateTime.parse( inputStop , f );
Calculate elapsed time. We should get one second less than 24 hours.
Duration d = Duration.between( zdtStart , zdtStop );
Apparently you want the count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z. First extract the building-block class, Instant, from each ZonedDateTime. An Instant represents a moment in UTC. This class lets you interrogate for the count since epoch. Note that java.time classes resolve to nanoseconds. So asking for milliseconds can result in data loss, ignoring any microseconds or nanoseconds.
Instant start = zdtStart.toInstant() ;
Instant stop = zdtStop.toInstant() ;
long millisStart = start.toEpochMilli() ;
long milliStop = stop.toEpochMilli() ;
Dump to console.
System.out.println( "zdtStart = " + zdtStart );
System.out.println( "zdtStop = " + zdtStop );
System.out.println( "d = " + d );
System.out.println( "start = " + start );
System.out.println( "stop = " + stop );
System.out.println( "millisStart = " + millisStart );
System.out.println( "milliStop = " + milliStop );
zdtStart = 2019-10-24T00:00Z[UTC]
zdtStop = 2019-10-24T23:59:59Z[UTC]
d = PT23H59M59S
start = 2019-10-24T00:00:00Z
stop = 2019-10-24T23:59:59Z
millisStart = 1571875200000
milliStop = 1571961599000
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.
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….
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.
You need to use the following date format:
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy hh:mm:ss.SSS a zzz",Locale.US);
For AM/PM Marker, 'a' is used. For reference
e.g.
import java.util.*;
import java.text.*;
public class Main
{
public static void main(String[] args) {
try{
String dt = "Oct 24 2019 12:00:00.000 AM UTC";
String dt1="Oct 24 2019 11:59:59.000 PM UTC";
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy hh:mm:ss.SSS a zzz",Locale.US);
Date date = df.parse(dt);
Date date1 = df.parse(dt1);
long epoch = date.getTime();
long epoch1 = date1.getTime();
System.out.println(epoch);
System.out.println(epoch1);
}catch(Exception e){
e.printStackTrace();
}
}
}
output:
1571918400000
1571918399000

How to reformat time format?

I am working on android project and i receive from API the time in format like this "10:12:57 am" (12 hour format) and I want to display it in format "10:12" just like this (on a 24 hour clock). How to reformat that time?
So 12:42:41 am should become 00:42. And 02:13:39 pm should be presented as 14:13.
Using java.time (Modern Approach)
String str = "10:12:57 pm";
DateTimeFormatter formatter_from = DateTimeFormatter.ofPattern( "hh:mm:ss a", Locale.US ); //Use pattern symbol "hh" for 12 hour clock
LocalTime localTime = LocalTime.parse(str.toUpperCase(), formatter_from );
DateTimeFormatter formatter_to = DateTimeFormatter.ofPattern( "HH:mm" , Locale.US ); // "HH" stands for 24 hour clock
System.out.println(localTime.format(formatter_to));
See BasilBourque answer below and OleV.V. answer here for better explanation.
Using SimpleDateFormat
String str = "10:12:57 pm";
SimpleDateFormat formatter_from = new SimpleDateFormat("hh:mm:ss a", Locale.US);
//Locale is optional. You might want to add it to avoid any cultural differences.
SimpleDateFormat formatter_to = new SimpleDateFormat("HH:mm", Locale.US);
try {
Date d = formatter_from.parse(str);
System.out.println(formatter_to.format(d));
} catch (ParseException e) {
e.printStackTrace();
}
If your input is 10:12:57 am, output will be 10:12. And if string is 10:12:57 pm, output will be 22:12.
tl;dr
LocalTime // Represent a time-of-day, without a date and without a time zone.
.parse( // Parse an input string to be a `LocalTime` object.
"10:12:57 am".toUpperCase() , // The cultural norm in the United States expects the am/pm to be in all-uppercase. So we convert our input value to uppercase.
DateTimeFormatter.ofPattern( "hh:mm:ss a" , Locale.US ) // Specify a formatting pattern to match the input.
) // Returns a `LocalTime` object.
.format( // Generate text representing the value in this date-time object.
DateTimeFormatter.ofPattern( "HH:mm" , Locale.US ) // Note that `HH` in uppercase means 24-hour clock, not 12-hour.
) // Returns a `String`.
10:12
java.time
The modern approach uses the java.time classes that years ago supplanted the terrible Date & Calendar & SimpleDateFormat classes.
The LocalTime class represents a time-of-day in a generic 24-hour day, without a date and without a time zone.
Parse your string input as a LocalTime object.
String input = ( "10:12:57 am" );
DateTimeFormatter fInput = DateTimeFormatter.ofPattern( "HH:mm:ss a" , Locale.US );
LocalTime lt = LocalTime.parse( input.toUpperCase() , fInput ); // At least in the US locale, the am/pm is expected to be in all uppercase: AM/PM. So we call `toUppercase` to convert input accordingly.
lt.toString(): 10:12:57
Generate a String with text in the hour-minute format you desire. Note that HH in uppercase means 24-hour clock.
DateTimeFormatter fOutput = DateTimeFormatter.ofPattern( "HH:mm" , Locale.US );
String output = lt.format( fOutput );
output: 10:12
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….
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.
Try this:
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm:ss a");
try {
Date date = parseFormat.parse("10:12:57 pm");
System.out.println(parseFormat.format(date) + " = " + displayFormat.format(date));
}
catch (Exception e) {
e.printStackTrace();
}
The gives:
10:12:57 pm = 22:12
You can use such formatters:
SimpleDateFormat formatterFrom = new SimpleDateFormat("hh:mm:ss aa");
SimpleDateFormat formatterTo = new SimpleDateFormat("HH:mm");
Date date = formatterFrom.parse("10:12:57 pm");
System.out.println(formatterTo.format(date));
String str ="10:12:57 pm";
SimpleDateFormat formatter_from = new SimpleDateFormat("hh:mm:ss aa", Locale.US);
SimpleDateFormat formatter_to = new SimpleDateFormat("HH:mm",Locale.US);
try {
Date d = formatter_from.parse(str);
System.out.println(formatter_to.format(d));
} catch (ParseException e) {
e.printStackTrace();
}

How to convert a Gregorian calendar date format to Julian date format?

I want to convert dd-MON-yyyy to Julian date as part of SQL query against JDE. It would be of great help if anyone could guide on how to achieve this.
new JulianDate().ConvertToJulian(date1) worked when date1 was in mm/dd/yyyy format. But when date1 is in dd-MON-yyyy format i get the error:
java.text.ParseException: Unparseable date: "16-Mar-2017"
In JDE, the date is stored in Julian Format.
Please note here mm/dd/yyyy and dd-MON-yyyy are all in string format.
Hence DateFormat, SimpleDateFormat, etc cannot be applied.
Also in SQL i believe it is dd-MON-yyyy format and not dd-MMM-yyyy format.
You need to use the dd-MMM-yyyy format for this.
Take a look at the code below. This converts given date format to Julian format.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatConverter {
private String inputDateFormat;
private String outputDateFormat;
private DateFormatConverter (String inputDateFormat, String outputDateFormat) {
this.inputDateFormat = inputDateFormat;
this.outputDateFormat = outputDateFormat;
}
private String convert(String inputDate) throws ParseException {
SimpleDateFormat idf = new SimpleDateFormat(inputDateFormat);
SimpleDateFormat odf = new SimpleDateFormat(outputDateFormat);
Date date = idf.parse(inputDate);
String outputDate = odf.format(date);
return outputDate;
}
public static String toJulian(String inputFormat, String inputDate) throws ParseException {
String suffixFormat = "yyDDD";
String prefixFormat = "yyyy";
String suffix = new DateFormatConverter(inputFormat, suffixFormat).convert(inputDate);
int centuryPrefix = Integer.parseInt(new DateFormatConverter(inputFormat, prefixFormat).convert(inputDate).substring(0, 2))-19;
return centuryPrefix+suffix;
}
public static void main(String[] args) throws ParseException {
String jd = DateFormatConverter.toJulian("dd-MMM-yyyy", "01-Jan-2017");
System.out.println(jd);
}
}
Extra:
Refer to this info about Julian dates:
https://docs.oracle.com/cd/E26228_01/doc.93/e21961/julian_date_conv.htm#WEAWX259
Hope this helps!
tl;dr
LocalDate.parse(
"16-Mar-2017" ,
DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US )
)
java.time
The modern approach is with java.time classes. Avoid the notoriously troublesome old date-time classes, now legacy.
Parse date string
Parse the date string by defining a formatting pattern to match. Specify a Locale for human language to use in translating the name of the month.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US );
String input = "16-Mar-2017" ;
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate localDate = LocalDate.parse( input , f );
JD Edwards EnterpriseOne date format
If by JDE you meant “JD Edwards EnterpriseOne”, those systems use an unusual format for representing a date-only value as a string, CYYDDD where:
C = Century, 0 for 1900s, 1 for 2000s. Add to 19 to get century number, multiply by 100 to get year number.
YY = Year of the century.
DDD = Day of year, running 1 to 365 (or 366 in Leap Year).
Let's build up a String in that format.
// Build output in CYYDDD format used by JD Edwards EnterpriseOne.
int c = ( ( localDate.getYear ( ) / 100 ) - 19 );
String yy = ( String.valueOf ( localDate.getYear ( ) ) ).substring ( 2 ); // Substring of positions 3-4, index numbering is 2.
String ddd = String.format ( "%03d", localDate.getDayOfYear ( ) );
String output = c + yy + ddd ;
Dump to console.
System.out.println ("input: " + input );
System.out.println ( "output: " + output );
When run.
input: 16-Mar-2017
output: 117075
Now go the other direction, parsing a JDE date string to get a LocalDate. We extract the century code of 1, add it to 19, and multiply by a hundred, and lastly add the two digits for year-of-century. From that integer year number we create a Year object. By feeding that Year object the parsed integer number for day-of-year, we get a LocalDate object.
// Going the other direction, parsing CYYDDD to get a `LocalDate`.
String cyyddd = "117075";
String c_ = cyyddd.substring ( 0, 0 + 1 ); // Index-counting, zero-based.
String yy_ = cyyddd.substring ( 1, 1 + 2 );
String ddd_ = cyyddd.substring ( 3 );
Year year = Year.of ( ( ( Integer.valueOf ( c_ ) + 19 ) * 100 ) + Integer.valueOf ( yy_ ) );
LocalDate ld = year.atDay( Integer.valueOf ( ddd_ ));
Dump to console.
System.out.println ("cyyddd: " + cyyddd );
System.out.println ("ld: " + ld );
cyyddd: 117075
ld: 2017-03-16
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….
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.
I did the following:
String date1="dd-MMM-yyyy";
String date2="MM/dd/yyyy";
SimpleDateFormat idf = new SimpleDateFormat(date1);
SimpleDateFormat odf = new SimpleDateFormat(date2);
Date dateFrom = idf.parse(fromDate);
Date dateTo = idf.parse(toDate);
And then to convert to Julian Date i used:
new JulianDate().ConvertToJulian(odf.format(dateFrom));
new JulianDate().ConvertToJulian(odf.format(dateTo));
Hoping somebody would find it useful in future.

Get day, month and year separately using SimpleDateFormat

I have a SimleDateFormat like this
SimpleDateFormat format = new SimpleDateFormat("MMM dd,yyyy hh:mm");
String date = format.format(Date.parse(payback.creationDate.date));
I'm giving date with the format like "Jan,23,2014".
Now, I want to get day, month and year separately. How can I implement this?
If you need to get the values separately, then use more than one SimpleDateFormat.
SimpleDateFormat dayFormat = new SimpleDateFormat("dd");
String day = dayFormat.format(Date.parse(payback.creationDate.date));
SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
String month = monthFormat .format(Date.parse(payback.creationDate.date));
etc.
SimpleDateFormat format = new SimpleDateFormat("MMM dd,yyyy hh:mm", Locale.ENGLISH);
Date theDate = format.parse("JAN 13,2014 09:15");
Calendar myCal = new GregorianCalendar();
myCal.setTime(theDate);
System.out.println("Day: " + myCal.get(Calendar.DAY_OF_MONTH));
System.out.println("Month: " + myCal.get(Calendar.MONTH) + 1);
System.out.println("Year: " + myCal.get(Calendar.YEAR));
Wow, SimpleDateFormat for getting string parts? It can be solved much easier if your input string is like "Jan,23,2014":
String input = "Jan,23,2014";
String[] out = input.split(",");
System.out.println("Year = " + out[2]);
System.out.println("Month = " + out[0]);
System.out.println("Day = " + out[1]);
Output:
Year = 2014
Month = Jan
Day = 23
But if you really want to use SimpleDateFormat because of some reason, the solution will be the following:
String input = "Jan,23,2014";
SimpleDateFormat format = new SimpleDateFormat("MMM,dd,yyyy");
Date date = format.parse(input);
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
calendar.setTime(date);
System.out.println(calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
System.out.println(new SimpleDateFormat("MMM").format(calendar.getTime()));
Output:
2014
23
Jan
The accepted answer here suggests to use more than one SimpleDateFormat, but it's possible to do this using one SimpleDateFormat instance and calling applyPattern.
Note: I believe this post would also be helpful for those who were searching for setPattern() just like me.
Date date=new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
simpleDateFormat.applyPattern("dd");
System.out.println("Day : " + simpleDateFormat.format(date));
simpleDateFormat.applyPattern("MMM");
System.out.println("Month : " + simpleDateFormat.format(date));
simpleDateFormat.applyPattern("yyyy");
System.out.println("Year : " + simpleDateFormat.format(date));
tl;dr
Use LocalDate class.
LocalDate
.parse(
"Jan,23,2014" ,
DateTimeFormatter.ofPattern( "MMM,dd,uuuu" , Locale.US )
)
.getYear()
… or .getMonthValue() or .getDayOfMonth.
java.time
The other Answers use outmoded classes. The java.time classes supplant those troublesome old legacy classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
String input = "Jan,23,2014";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM,d,uuuu" );
LocalDate ld = LocalDate.parse( input , f );
Interrogate for the parts you want.
int year = ld.getYear();
int month = ld.getMonthValue();
int dayOfMonth = ld.getDayOfMonth();
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….
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.
Use this to parse "Jan,23,2014"
SimpleDateFormat fmt = new SimpleDateFormat("MMM','dd','yyyy");
Date dt = fmt.parse("Jan,23,2014");
then you can get whatever part of the date.
Are you accepting this ?
int day = 25 ; //25
int month =12; //12
int year = 1988; // 1988
Calendar c = Calendar.getInstance();
c.set(year, month-1, day, 0, 0);
SimpleDateFormat format = new SimpleDateFormat("MMM dd,yyyy hh:mm");
System.out.println(format.format(c.getTime()));
Display as Dec 25,1988 12:00
UPDATE : based on Comment
DateFormat format = new SimpleDateFormat("MMM");
System.out.println(format.format(format.parse("Jan,23,2014")));
NOTE: Date.parse() is #deprecated and as per API it is recommend to use DateFormat.parse
public static String getDate(long milliSeconds, String dateFormat) {
// Create a DateFormatter object for displaying date in specified
// format.
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat,
Locale.getDefault());
// Create a calendar object that will convert the date and time value in
// milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}

Categories

Resources