I had written a function for Adding time as given below
private void Delay15Minute() {
String pkManifest = manifest.pkManifestNo;
manifest_helper = new manifest_helper(this);
cursor = manifest_helper.GetDeliveries(pkManifest);
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
cursor.getString(cursor.getColumnIndex("PKDelivery"));
// String
// RevisedTime=cursor.getString(cursor.getColumnIndex("RevisedEstimatedDeliveryTime"));
String RevisedTime = "12:55";
// get hour and minute from time string
StringTokenizer st1 = new StringTokenizer(RevisedTime, ":");
int j = 0;
int[] val = new int[st1.countTokens()];
// iterate through tokens
while (st1.hasMoreTokens()) {
val[j] = Integer.parseInt(st1.nextToken());
j++;
}
// call time add method with current hour, minute and minutesToAdd,
// return added time as a string
String date = addTime(val[0], val[1], 15);
// Tioast the new time
Toast.makeText(this, "date is =" + date, Toast.LENGTH_SHORT).show();
}
}
public String addTime(int hour, int minute, int minutesToAdd) {
Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
calendar.add(Calendar.MINUTE, minutesToAdd);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
String date = sdf.format(calendar.getTime());
return date;
}
I am getting the oupt of this as 01:10 as 12 hours fromat...
I need to get it in 13:10 format ie 24 hour format.....Please help me
You used hh in your SimpleDateFormat pattern. Thats the 12 hour format. Use kk instead, that gives you the hours of the day in a 24 hour format. See SimpleDateFormat.
Simply create the instance of Calendar and get 24 hr time by,
Calendar c = Calendar.getInstance();
int Hr24=c.get(Calendar.HOUR_OF_DAY);
int Min=c.get(Calendar.MINUTE);
Use this code
long date = System.currentTimeMillis();
SimpleDateFormat date1 = new SimpleDateFormat("dd-MM-yyyy"); // for current date
SimpleDateFormat time1 = new SimpleDateFormat("kk:mm:ss"); // for 24 hour time
SimpleDateFormat time2 = new SimpleDateFormat("hh:mm:ss"); // for 12 hour time
String dateString = date1.format(date); //This will return current date in 31-12-2018 format
String timeString1 = time1.format(date); //This will return current time in 24 Hour format
String timeString2 = time2.format(date); //This will return current time in 12 Hour format
Log.e("TAG_1", "24 hour Time - " + timeString1);
Log.e("TAG_1", "24 hour Time - " + timeString1);
Log.e("TAG_1", "dd-MM-yyyy Date format - " + dateString);
than open your logcat to check result.
Related
I have a start date (day, month, year) and need the date say 4 weeks from that date. How can I calculate that? I know how to find the difference between two dates using Calendar so I assume I'm not too far from the answer... Thank you!!!
edit:
This is the final code I wound up using. It returns a String whose value is a date span formatted "MM/dd/YYYY - MM/dd/YYYY"
#SuppressLint("SimpleDateFormat")
private String getSessionDate(int position) {
MySession ms = mSessionList.get(position);
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Calendar calendar = Calendar.getInstance();
calendar.set(ms.getStartYear(), ms.getStartMonth(), ms.getStartDay());
Date startDate = calendar.getTime();
String durationString = ms.getDurationString(); // Format is "## weeks"
int i = 0;
while (Character.isDigit(durationString.charAt(i))) {
i++;
}
int weeks = Integer.parseInt(durationString.substring(0, i));
calendar.add(Calendar.WEEK_OF_YEAR, weeks);
return (format.format(startDate) + " - " + format.format(calendar.getTime()));
}
You can use Calender instance for that.
Calendar calendar = Calendar.getInstance();
calendar.setTime(currentdate);
calendar.add(Calendar.DAY_OF_YEAR, no_of_days)
Date newDate = calendar.getTime();
You can calculate the date by adding or subtracting the no of days
Example :
Get date after 1 week
calendar.add(Calendar.DAY_OF_YEAR, 7);
Get date before 1 week
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date date=null;
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = originalFormat.parse(strDate); // strDate is your date from which you want to get date after 4 weeks
} catch (Exception e) {
e.printStackTrace();
}
long timeFor4week=4*7*24 * 60 * 60 * 1000; /// here 24*60*60*1000 =24 hours i.e 1 day
long timeAfter4week=date.getTime()+timeFor4week;
String finalDateString=originalFormat.format(new Date(timeAfter4week));
So you can get day after 4 weeks.
I am writing an application in which I have to display a date . Now I want to convert that date into Year and Month from the Current Date.
My Date is Like - 29/03/2017.
I want to convert this date into Year and Months.
Sorry I think you are not able to understand my question. I want the Difference of current date and above date in year and months.
Sorry for my explanation.
You can use Joda Time and compute a Period between two LocalDate values (which is what you've got here) using months and years as the units.
example
LocalDate dob = new LocalDate(1992, 12, 30);
LocalDate date = new LocalDate(2010, 12, 29);
Period period = new Period(dob, date, PeriodType.yearMonthDay());
System.out.println(period.getYears() + " years and " +
period.getMonths() + " months");
I found my answer using Calender class .
First i find the difference between two days and using that days i found the years and months.
Here i post my code, which i think help to others.
int days = Integer.parseInt(Utility.getDateDiffString("29/03/2017"));
int years = days/365;
int remainingDays = days - (365*years);
int months = remainingDays/30;
getDateDiffString() Method. In this method we need to pass end date
public static String getDateDiffString(String endDate)
{
try
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date dateTwo = dateFormat.parse(endDate);
long timeOne = cal.getTimeInMillis();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return "" + delta + "";
}
else {
delta *= -1;
return "" + delta + "";
}
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
if your date's format is fixed, you can do it like this :
String myDate = "29/03/2017";
String newDate = myDate.subString(6, 10) + "-" + myDate.subString(3, 5)
this method to convert the normal string to date format
String currentDateString = "02/27/2012 17:00:00";
SimpleDateFormat sd = new SimpleDateFormat("mm/dd/yyyy HH:mm:ss");
Date currentDate = sd.parse(currentDateString);
after that you get the formal method
You Should use SimpleDateFormate !
For Example:--- You can get time & Date as you want:-
Date email_date = m.getSentDate();// this is date which you are getting
DateFormat date = new SimpleDateFormat("EEE MMM yyyy");
DateFormat time = new SimpleDateFormat("hh:mm aa");
String date_str=date.format(email_date);
String time_str=time.format(email_date);
Use Java Calendar class to get year from date
Calendar c=Calendar.getInstance();
SimpleDateFormat simpleDateformat=new SimpleDateFormat("yyyy MMM");
System.out.println(simpleDateformat.format(c.getTime()));
To get difference between two date
int diffInDays = (int)( (newerDate.getTime() - olderDate.getTime())
/ (1000 * 60 * 60 * 24) )
long timeDiff = (d1.getTime() - d2.getTime());
String diff=String.format("%d year(s) %d day(s) %d hour(s) %d min(s) %d sec(s)",(TimeUnit.MILLISECONDS.toDays(timeDiff)/365),TimeUnit.MILLISECONDS.toDays(timeDiff)%365,
TimeUnit.MILLISECONDS.toHours(timeDiff)
- TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS
.toDays(timeDiff)),
TimeUnit.MILLISECONDS.toMinutes(timeDiff)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(timeDiff)),
TimeUnit.MILLISECONDS.toSeconds(timeDiff)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(timeDiff)));
System.out.println(diff);
Specify correct date here in d1 & d2.Then you will get right answer of difference
First put your Date into a String variable as:
String dateToConvert = "29/03/2017";
Instantiate Calendar as:
Calendar convertedDate = Calendar.getInstance();
Set that date to calendar
convertedDate.set(dateToConvert);<br/>
Then use this line:
String datePicked = DateFormat.getDateInstance().format(convertedDate.getTime());
Output: Mar 29, 2017
This is how i get the phone's date, but it prompts me with a parseException, what's the problem?
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(new Date());
Date localDate = sdf.parse(date);
new Date(0) is not the current date/time. You should use new Date(). ParseException should go away then. If you wanna know why you got that, simply debug your program and have a look at what new Date(0) gives as a String, you'll know why it fails to be parsed.
Date now = new Date();
Date alsoNow = Calendar.getInstance().getTime();
String nowAsString = new SimpleDateFormat("yyyy-MM-dd").format(now);
That works. And that too:
Date christmas = new SimpleDateFormat("yyyy-MM-dd").parse("2012-12-25");
By the way, make sure you are using java.util.Date and not java.sql.Date
Calendar now = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String nowDate = formatter.format(now.getTime());
String[] separateCurrentDate = nowDate.split("-");
String year = separateCurrentDate[0];
String month = separateCurrentDate[1];
String day = separateCurrentDate[2];
int currentYear = Integer.parseInt(year);
int currentMonth = Integer.parseInt(month);
int currentDay = Integer.parseInt(day);
and then store y,m,d one by one into a Date type onject
Date now = new Date();
Date alsoNow = Calendar.getInstance().getTime();
String nowAsString = new SimpleDateFormat("yyyy-MM-dd").format(now);
currentdate = (TextView)findViewById(R.id.textcntdate);
currentdate.setText(nowAsString);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + ":" + seconds;
And then also here is another link on this
Display the current time and date in an Android application
I have 09:30 as a time retrieved from a database, I need to add 15 minutes to get it as 09:45.
Is there a function for adding time?
String RevisedTime=cursor.getString(cursor.getColumnIndex("RevisedEstimatedDeliveryTime"));
// get hour and minute from time string
StringTokenizer st1 = new StringTokenizer(RevisedTime, ":");
int j = 0;
int[] val = new int[st1.countTokens()];
// iterate through tokens
while (st1.hasMoreTokens()) {
val[j] = Integer.parseInt(st1.nextToken());
j++;
}`enter code here`
// call time add method with current hour, minute and minutesToAdd,
// return added time as a string
String dateRevisedEstimatedDeliveryTime = addTime(val[0], val[1], 15);
public String addTime(int hour, int minute, int minutesToAdd) {
Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
calendar.add(Calendar.MINUTE, minutesToAdd);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String date = sdf.format(calendar.getTime());
return date;
}
http://download.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html has what you need, using its add() method.
Try like this
final Calendar cld = Calendar.getInstance();
cld.setTimeInMillis(time);
cld.add(Calendar.MINUTE,15)
use Calendar.add(Calendar.MINUTE,15) to get that
i have a android timepicker, and i need to get his time in java code, and transform it into a string with this appereance: "08:00:00" (hours, mins, secs)
can someone help me to do it in a easy way?
code example will be appreciated
TimePicker t = new TimePicker(this);
String formattedTime = "";
int hour = t.getCurrentHour();
String sHour = "00";
if(hour < 10){
sHour = "0"+hour;
} else {
sHour = String.valueOf(hour);
}
int minute = t.getCurrentMinute();
String sMinute = "00";
if(minute < 10){
sMinute = "0"+minute;
} else {
sMinute = String.valueOf(minute);
}
formattedTime = sHour+":"+sMinute+":"+"00"; // Sorry you can't get seconds from a TimePicker
TimePicker has 2 methods available to get the set time. getCurrentHour and getCurrentMinute.
So outputting this as a string shouldn't be too hard.
String s;
Format formatter;
Calendar calendar = Calendar.getInstance();
// tp = TimePicker
calendar.set(Calendar.HOUR_OF_DAY, tp.getCurrentHour());
calendar.set(Calendar.MINUTE, tp.setCurrentMinutes());
calendar.clear(Calendar.SECOND); //reset seconds to zero
formatter = new SimpleDateFormat("HH:mm:ss");
s = formatter.format(calendar.getTime()); // 08:00:00
By the way, lowercase hh will get you a 12 hour clock.
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
String formatted = format.format(date); // date is a long in milliseconds
Just use SimpleDateFormat to format date and time .
Calendar cal=new Calendar();
SimpleDateFormat frmDate=SimpleDateFormat("dd-MM-yyyy");
String s=frmDate.format(cal.getTime());
SimpleDateFormat frmTime=SimpleDateFormat("HH:MM:SS");
String t=frmTime.formate(cal.getTime());
http://developer.android.com/reference/java/text/SimpleDateFormat.html
http://developer.android.com/reference/java/text/DateFormat.html
Also check out DateUtils, very useful.
Please find the below code:
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
String formatted = format.format(date); // date is a long in milliseconds