how to get difference between two date_time - java

I want to get the difference in seconds between end_date_time and system_date_time using JAVA, for example:
if
end_date_time = 2015-02-21 13:00:00
system_date_time = 2015-02-20 13:00:00
then
difference = 86400
Please tell how can I do this?

If you have a Date type already, it's as simple as:
(System.currentTimeMillis() - myDate.getTime()) / 1000;
If you have a string and need to convert it to a date, you use a SimpleDateFormat instance:
String dateString = "2015-02-21 13:00:00" // end_date_time
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
Date myDate = sdf.parse(dateString);
If you're using Java8, this is much easier:
String dateString = "2007-12-03T10:15:30.00Z";
Instant.now().until(Instant.parse(dateString), ChronoUnit.SECONDS);
Your dateString must be parseable in the ISO format, though:
"yyyy-mm-ddThh:mm:ss.SZ"

Related

How can I convert multiple iso date format with the same function to date in java?

I am creating a DSL with ANTLR 4, and I wonder if it is possible to convert several date format (string) to date with the same function without passing the format for example if my DSL is like that
date1 = "2020-05-08"
date2 = "2020/05/08"
date3 = "20200508"
...
and in my java code I convert the string directly to date without knowing the format for example
Date date1 = convertToDate(date1);
Date date2 = convertToDate(date2);
Date date1 = convertToDate(date3);
instead of writing
Date date1 = convertToDate(date1,"yyyy-mm-dd");
Date date2 = convertToDate(date2,"yyyy/mm/dd");
Date date1 = convertToDate(date3,"yyyymmdd");
Since Java 8, which introduced the new Date and Time API, you are no longer advised to use Date, Calendar, SimpleDateFormat and so on. Those are now legacy types.
Also, if you intend to parse the month, you are supposed to use MM instead of mm (which indicates minutes).
With the new Date and Time API, you could use DateTimeFormatter with optional patterns using [ and ]. Then you can parse the string dates to LocalDate instances, as shown below:
DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder()
.appendPattern("[yyyy-MM-dd]")
.appendPattern("[yyyy/MM/dd]")
.appendPattern("[yyyyMMdd]")
.toFormatter();
LocalDate date1 = LocalDate.parse("2020-05-08", dateFormatter);
LocalDate date2 = LocalDate.parse("2020/05/08", dateFormatter);
LocalDate date3 = LocalDate.parse("20200508", dateFormatter);
System.out.println(date1);
System.out.println(date2);
System.out.println(date3);
In the example you've passed you can remove all non digit symbols to use only one convert function. Ex:
date1 = "2020-05-08"
date2 = "2020/05/08"
date3 = "20200508"
...
dateN = removeSymbols(dateN);
Date date = convertToDate(dateN,"yyyymmdd");
To remove the non digit you can use this function:
dateN = dateN.replaceAll("\\D", "");
You should be able to accomplish this with a simple regex.
Pattern datePattern = Pattern.compile("^(?<Year>\\d{4})[/-]?(?<Month>\\d{2})[/-]?(?<Day>\\d{2})$")
Then build the date with the match groups.

Date convert in Java

I want to compare two dates, for that i convert the string to date format.But during the conversion the date format changed to "02/01/2013" and "03/01/2014".It makes error in my logic.any one please tell me to how to compare two days in my date format.
String fdate="01/02/2012";
String tdate="01/03/2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date frmdt=new Date(fdate);
String s1 = sdf.format(frmdt);
Date todt=new Date(tdate);
String s2 = sdf.format(todt);
Date frmdate = sdf.parse(s1);
Date todate = sdf.parse(s2);
if(frmdate.compareTo(todate)<=0){
//process;
}
Try this:
String fs = "01/02/2012";
String ts = "01/03/2013";
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
sdf.setLenient(false);
Date fdate = sdf.parse(fs);
Date tdate = sdf.parse(ts);
if (fdate.before(tdate) || f.date.equals(tdate)) {
//process;
}
You've got too much going on. It's much simpler.
It seems to me that you should be calling SimpleDateFormat.parse instead:
// Using the US locale will force the use of the Gregorian calendar, and
// avoid any difficulties with different date separator symbols etc.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // Avoid DST complications
sdf.setLenient(false);
Date fromDate = sdf.parse(fromDateText);
Date toDate = sdf.parse(toDateText);
// Alternatively: if (!fromDate.after(toDate))
if (fromDate.compareTo(toDate) <= 0) {
...
}
I'd actually suggest that you use Joda Time if at all possible, where you could use a LocalDate type to more accurately represent your data.
You're doing it wrong :)
String fdate="01/02/2012";
String tdate="01/03/2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date frmdate = sdf.parse(fdate);
Date todate = sdf.parse(tdate);
if(frmdate.compareTo(todate)<=0){
//process;
}
You were passing to Date a not parsed date with your format. Also Date(String) is deprecated. DateFormat.parse(String) is the correct one.

How to parse values returned by getDate() in java?

I have created a web service which returns the date of an event which is initially captured by the getDate() function. I want the date returned by this function (something along this format : 2013-05-17 14:52:00.943) to be parsed and shown to the user in the DD-MM-YYYY format.
Any suggestions? I haven't found any solution along this direction yet.
I have tried this code and it's work fine for me,Please Try my code below: Please upvote to Tarun also coz he gave almost right answer.just he did mistake that he passes cal.getTime() method instead of pDate
String formatDate = p.format(pDate);
and second mistake in format like"DD-MM-YYYY" but actual format is:
"dd-MM-yyyy" not "DD-MM-YYYY"
I have done changes in it and modify it.
String dateStr = "2013-05-16 14:52:00.943";
SimpleDateFormat c = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S"); // your web service format
Date pDate = c.parse(dateStr);
SimpleDateFormat p = new SimpleDateFormat("dd-MM-yyyy"); // your required format
String formatDate = p.format(pDate); // convert it in your required format
SimpleDateFormat formatter = new SimpleDateFormat("EEEE"); // Day format as you want EEE for like "Sat" and EEEE for like "Saturday"
String Day = formatter.format(pDate); // This will give you a day as your selected format
System.out.println("Date & Day>>>"+formatDate+" "+Day);
// For GMT format your format should be like this: "2013-05-16 14:52:00.943 GMT+05:30"
// Give it to me in GMT time.
c.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
System.out.println("GMT time: " + c.format(pDate));
Output:
Date & Day>>>16-05-2013 Thursday
GMT time: 2013-05-16 02:52:00.943 Greenwich Mean Time
Joda time:
you can download 2.0 jar file of joda time from here:
DateTimeFormatter jodaFormatter = ISODateTimeFormat.dateTime();
DateTime jodaParsed = jodaFormatter
.parseDateTime("2013-05-17T16:27:34.9+05:30");
Date date2 = jodaParsed.toDate();
System.out.println("Date & Day:" + jodaParsed.getDayOfMonth() + "-" + jodaParsed.getMonthOfYear() + "-" + jodaParsed.getYear() + " " + jodaParsed.getHourOfDay() + ":" + jodaParsed.getMinuteOfHour()+" "+jodaParsed.dayOfWeek().getAsText());
output:
Date & Day:17-5-2013 16:27 Friday
Hope it will work for you.
String dateStr = "2013-05-17 14:52:00.943";
SimpleDateFormat c = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
Date pDate = c.parse(dateStr);
SimpleDateFormat p = new SimpleDateFormat("dd-MM-yyyy");
String formatDate = p.format(pDate);
You can use Joda Time if you have colon in time offset.
DateTimeFormatter jodaFormatter = ISODateTimeFormat.dateTime();
DateTime jodaParsed = jodaFormatter.parseDateTime("2013-05-17T16:27:34.9+05:30");
Date date = jodaParsed.toDate();
Calendar c = Calendar.getInstance();
c.setTime(date);
c.get(Calendar.DATE));
More info about joda can be found here.
Use a SimpleDateFormat to parse the date and then print it out with a SimpleDateFormat withe the desired format.
Example:
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MM-yyyy");
Date date = format1.parse("05/18/2013");
System.out.println(format2.format(date));
Output:
11-05-2013
Edit:
Calendar cal = Calendar.getInstance();
cal.setTime(specific_date);
int dayOfMonth = cal.get(Calendar.DAY_OF_WEEK);
String dayOfMonthStr = String.valueOf(dayOfMonth);

Change time in DateFormat on Android

I have date and time extracted from JSON in following format
2013-01-16T13:43:11
I need to convert it to local time of Pakistan and add 5 hours to that time so the result is like:
06:43
How I can achieve this?
Assuming that "2013-01-16T13:43:11" is in GMT
String s = "2013-01-16T13:43:11";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = df.parse(s);
date = new Date(date.getTime() + 5 * 3600 * 1000);
String time = new SimpleDateFormat("HH:mm").format(date);
time will be in your local timezone, so if you are in Pakistan it will be OK
You can use SimpleDateFormat as below:
String strDate = null;
SimpleDateFormat dateFormatter = new SimpleDateFormat(
"hh:mm");
strDate = dateFormatter.format(yourDate);
Hope it helps.
java dateFormat is not threadsafe, use joda time lib instead:
Joda time lib download
you can use withZone method to change time with specific Timezone
DateTime userTime1 = new DateTime();
DateTime eventRecordTime = new DateTime();
userTime1 = DateTime.parse("2012-07-05T21:45:00+02:00");
eventRecordTime = DateTime.parse((String) jo.get("start_time"));
DateTimeZone dtz = userTime1.getZone();
System.out.println(eventRecordTime.withZone(dtz).toString());

Convert date into specific format

I am working on Java. I have a date for example: 20120328.
Year is 2012, month is 03 & day is 28.
I want to convert it into yyyy-MM-dd format.
I have tried it but it is not working.
How to do it?
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
String ourformat = formatter.format(date.getTime());
If you want other than "MM/dd/yyyy" then just change the format in SimpleDateFormat
Find some examples here.
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date date = (Date)formatter.parse("01/29/02");
Take a look here. You will need to use the SimpleDateFormat class.
First you create the format using substring like
String myDate = "20120328";
String myConvertedDate = myDate.substring(0,4) + "-" + myDate.substring(5,6) + "-" + myDate.substring(7);
This produces the date as 2012-03-28
Then use simple date format to convert that into date if required.
You can use this one for Date formatting
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
String ourformat = formatter.format(date.getTime());
And this one for getting TimeStamp
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Timestamp timestamp =timestamp=new Timestamp(System.currentTimeMillis());
String ourformat = formatter.format(timestamp);

Categories