How to add some time in the system time? - java

I am trying to get the system date by using the following code . Now i want after adding 123 minutes it should automatically add 2 in hours and three in minutes how is it possible?
I am using the following code.
try{
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
String s = sdf.format(date);
}
catch(Exception ex)
{
ex.printStackTrace();
}

Create a GregorianCalendar object: http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html add you hours/minutes/whatever you need to add and then get back a Date

This will work
DateFormat df = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
System.out.println(df.format(date));
long milSec=date.getTime();
long addMilSec=123*60*1000;
long sum=milSec+addMilSec;
Date d=new Date(sum);
System.out.println(df.format(d));

Create a Calendar object, instead of Date, and use add.
Example:
Calendar c = Calendar.getInstance();
c.add(Calendar.MINUTE, 123);
String s = sdf.format(c.getTime());

try like this
Calendar now = Calendar.getInstance();
now.setTime(YOUR_DATE_OBJECT);//pass your date here
now.add(Calendar.MINUTE, 50);//add 5o minutes
now.add(Calendar.SECOND, -50);// subtract 50 seconds

Related

Android: Calc duration of event from two strings

So I'm having a timestamp like for example this one =1570312800
and also the source gives me the start time and the end-time in string format, so let's say it's basically from 18:00 to 01:00 (6PM to 1AM)
I want to calculate the difference between the 2 strings (5 hours), convert that to milliseconds and add it to the timestamp.
Which gets me in trouble is the converting from STRING to MILLISECONDS.
Which would be the cleanest way?
Sample Code:
Calendar c1 = Calendar.getInstance(android.icu.util.TimeZone.getTimeZone("UTC"));
Calendar c2 = Calendar.getInstance(android.icu.util.TimeZone.getTimeZone("UTC"));
SimpleDateFormat sdf = new SimpleDateFormat("HHmm");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
try
{
c1.setTime(sdf.parse("20:00"));
c2.setTime(sdf.parse("1:00"));
}
catch (ParseException e)
{
e.printStackTrace();
}
Log.d("TIME DIFFERENCE", String.valueOf(c2.getTimeInMillis()-c1.getTimeInMillis()));
One way to go about this is by parsing the string to a SimpleDateFormat like below:
Calendar c1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
c1.setTime(sdf.parse("20:00"));
System.out.println(c1.getTimeInMillis());

JAVA gives me wrong Date Results on Several devices

I have a weird problem I used Java to get a current date but I am getting different results on several devices, on one correct & on another wrong.
Here is my code:
public String getCurrentDate() {
/// get date
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
Date date = new Date();
System.out.println(dateFormat.format(date)); //2017-11-13 18:20:46 correct time is 11am
return dateFormat.format(date);
}
On the device that gives the wrong result I set automatic time zone use network-provided time zone & time of the device is correct.
Are testing with real devices?
You can also try the Calendar Class that are from Android. for more info visit (https://developer.android.com/reference/java/util/Calendar.html)
Check the Example bellow:
Calendar current_time_cal = Calendar.getInstance();
current_time_cal.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
int hours = current_time.get(Calendar.HOUR);
int current_am_pm = current_time.get(Calendar.AM_PM);
current_time_cal.set(Calendar.HOUR_OF_DAY, (hours == 0)? 12 : hours);
current_time_cal.set(Calendar.MINUTE, current_time.get(Calendar.MINUTE));
current_time_cal.set(Calendar.SECOND, 0);
Try this:
Calendar c = Calendar.getInstance();
System.out.println("Current time: " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());
You can use this method to get current time from your device:
public String getCurrentDate() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
String date = sdf.format(calendar.getTime());
return date;
}
This method will return current date as string.

how to convert timestamp into hoursminandsec in java

I have a unix timestamp. I wanted to convert into hours,min and seconds.I wanted to acheive it in java.I tried this .But I am not sure how do i have to concatenate it to hours+min+sec
int day = (int)TimeUnit.SECONDS.toDays(timeStamp);
long hours = TimeUnit.SECONDS.toHours(timeStamp) - (day *24);
long minute = TimeUnit.SECONDS.toMinutes(timeStamp) - (TimeUnit.SECONDS.toHours(timeStamp)* 60);
long second = TimeUnit.SECONDS.toSeconds(timeStamp) - (TimeUnit.SECONDS.toMinutes(timeStamp) *60);
thanks,
Ramya.
You can use the Calendar class for this. You can format the time using SimpleDateFormat
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeStamp);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String dateString = sdf.format(calendar.getTime());
Date date = new Date ();
date.setTime((long)unix_time*1000);
SimpleDateFormat df = new SimpleDateFormat("hh:mm:ss a",Locale.ENGLISH);
System.out.println(df.format(date));

How can i increment my date by 1

I want to increment the date by one. I have the below code while running the code I am getting unparseable date finally I want the date as string in the format of MM-DD-YYYY.
But same program is working with the YYYY-MM-DD format but i want mydate in this format(MM-DD-YYYY)
String dt = schReq.getStartDate(); // Start date
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, days); // number of days to add
dt = sdf.format(c.getTime());
schReq.setStartDate(dt);
Can anyone please help me?
The code should be working fine as long as dt and days are correct. This gave me 12-18-2014:
String dt = "12-17-2014"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1); // number of days to add
dt = sdf.format(c.getTime());
You have to use two different DateFormats:
one for parsing the string and one for formatting.
String dt = schReq.getStartDate(); // Start date
SimpleDateFormat sdf_parser = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf_parser.parse(dt));
c.add(Calendar.DATE, days); // number of days to add
dt = sdf.format(c.getTime());
schReq.setStartDate(dt);

How to subtract X day from a Date object in Java?

I want to do something like:
Date date = new Date(); // current date
date = date - 300; // substract 300 days from current date and I want to use this "date"
How to do it?
Java 8 and later
With Java 8's date time API change, Use LocalDate
LocalDate date = LocalDate.now().minusDays(300);
Similarly you can have
LocalDate date = someLocalDateInstance.minusDays(300);
Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime
Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
Java 7 and earlier
Use Calendar's add() method
Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();
#JigarJoshi it's the good answer, and of course also #Tim recommendation to use .joda-time.
I only want to add more possibilities to subtract days from a java.util.Date.
Apache-commons
One possibility is to use apache-commons-lang. You can do it using DateUtils as follows:
Date dateBefore30Days = DateUtils.addDays(new Date(),-30);
Of course add the commons-lang dependency to do only date subtract it's probably not a good options, however if you're already using commons-lang it's a good choice. There is also convenient methods to addYears,addMonths,addWeeks and so on, take a look at the api here.
Java 8
Another possibility is to take advantage of new LocalDate from Java 8 using minusDays(long days) method:
LocalDate dateBefore30Days = LocalDate.now(ZoneId.of("Europe/Paris")).minusDays(30);
Simply use this to get date before 300 days, replace 300 with your days:
Date date = new Date(); // Or where ever you get it from
Date daysAgo = new DateTime(date).minusDays(300).toDate();
Here,
DateTime is org.joda.time.DateTime;
Date is java.util.Date
Java 8 Time API:
Instant now = Instant.now(); //current date
Instant before = now.minus(Duration.ofDays(300));
Date dateBefore = Date.from(before);
As you can see HERE there is a lot of manipulation you can do. Here an example showing what you could do!
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
//Add one day to current date.
cal.add(Calendar.DATE, 1);
System.out.println(dateFormat.format(cal.getTime()));
//Substract one day to current date.
cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println(dateFormat.format(cal.getTime()));
/* Can be Calendar.DATE or
* Calendar.MONTH, Calendar.YEAR, Calendar.HOUR, Calendar.SECOND
*/
With Java 8 it's really simple now:
LocalDate date = LocalDate.now().minusDays(300);
A great guide to the new api can be found here.
In Java 8 you can do this:
Instant inst = Instant.parse("2018-12-30T19:34:50.63Z");
// subtract 10 Days to Instant
Instant value = inst.minus(Period.ofDays(10));
// print result
System.out.println("Instant after subtracting Days: " + value);
I have created a function to make the task easier.
For 7 days after dateString: dateCalculate(dateString,"yyyy-MM-dd",7);
To get 7 days upto dateString: dateCalculate(dateString,"yyyy-MM-dd",-7);
public static String dateCalculate(String dateString, String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
try {
cal.setTime(s.parse(dateString));
} catch (ParseException e) {
e.printStackTrace();
}
cal.add(Calendar.DATE, days);
return s.format(cal.getTime());
}
You may also be able to use the Duration class. E.g.
Date currentDate = new Date();
Date oneDayFromCurrentDate = new Date(currentDate.getTime() - Duration.ofDays(1).toMillis());
You can easily subtract with calendar with SimpleDateFormat
public static String subtractDate(String time,int subtractDay) throws ParseException {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
cal.setTime(sdf.parse(time));
cal.add(Calendar.DATE,-subtractDay);
String wantedDate = sdf.format(cal.getTime());
Log.d("tag",wantedDate);
return wantedDate;
}

Categories