I have a String timme = "13:10". I was wondering how would I best go about getting the hours and minutes and converting them into integers. i.e. int hours = 13 , int minute = 10. I know a for-loop wouldn't be the most efficient way, is there anything simpler?
Try this way, by split() method,
String timme = "13:10";
String[] time = timme.split ( ":" );
int hour = Integer.parseInt ( time[0].trim() );
int min = Integer.parseInt ( time[1].trim() );
Better use Date and DateFormat:
String time = "13:10";
DateFormat sdf = new SimpleDateFormat("HH:mm"); // or "hh:mm" for 12 hour format
Date date = sdf.parse(time);
date.getHours(); // int
date.getMinutes(); // int
You can try this...
String time = "13:10";
SimpleDateFormat formatter = = new SimpleDateFormat("hh:mm");
Date dTime = formatter.parse(time);
int hour = dTime.getHours();
int minute = dTime.getMinutes();
You could use Calendar object of java instead of Date object,
SimpleDateFormat dateFormatter = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
try {
Calendar c = Calendar.getInstance();
c.setTime(dateFormatter.parse("07:30"));
String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
String mintue = String.valueOf(c.get(Calendar.MINUTE));
System.out.println("Hour: " + hour);
System.out.println("Minute: " + mintue);
} catch (ParseException e) {
e.printStackTrace();
}
JAVA 8
LocalTime localTime = LocalTime.parse("13:10", DateTimeFormatter.ofPattern("HH:mm"));
int hour = localTime.getHour();
int minute = localTime.getMinute();
System.out.println("Hours : "+hour +" Minutes : "+minute);
Related
I getting two date from calendars.It writing into a string builder.I want to getting difference between two date also I want to keep the number of days remaining between times,except weekends.
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
if (cur == DATE_DIALOG_ID) {
// set selected date into textview
permitDate = new StringBuilder().append(day).append(".").append(month + 1).append(".").append(year).append(" ").toString();
tvDisplayDate.setText("Date : " + permitDate);
} else {
startDate = new StringBuilder().append(day).append(".").append(month + 1) .append(".").append(year).append(" ").toString();
tvDisplayDate2.setText("Date : " + startDate);
}
}
};
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 1985);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
long days = diff / (24 * 60 * 60 * 1000);
To Parse the date from a string, you could use
String strThatDay = "1985/08/25";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
d = formatter.parse(strThatDay);//catch exception
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d); //rest is the same....
Use JodaTime library to find the difference between dates.
For more information follow the instructions Use Joda Time.
Is there any other easy way to convert "Aug/2016" to "08/2016" in java?
My Logic is working fine, but seems too vague.
String myDate = "Aug/2016";
String str = myDate.split("/")[0];
Date date;
try {
date = new SimpleDateFormat("MMMM").parse(str);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println("##### ----- month in number : " +cal.get(Calendar.MONTH+1));
int year = Calendar.getInstance().get(Calendar.YEAR);
int mnth = cal.get(Calendar.MONTH) + 1;
str = String.valueOf(mnth+"/"+year);
System.out.println("##### ----- new selected date : " +str);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
suggestions please!...
Simply use SimpleDateFormat:
String myDate = "Aug/2016";
SimpleDateFormat parser = new SimpleDateFormat("MMM/yyyy");
SimpleDateFormat formatter = new SimpleDateFormat("MM/yyyy");
System.out.println(formatter.format(parser.parse(myDate)));
I have a date format like "SA25MAY"; I need to convert it into date time variable and then I want to add one day in that. And then I need to return the answer in same format. Please do some needful
try {
String str_date = "SA25MAY";
DateFormat formatter;
Date date;
formatter = new SimpleDateFormat("ddd-dd-MMM");
date = (Date) formatter.parse(str_date);
System.out.println("Today is " + date);
} catch (Exception e) {
e.printStackTrace();
}
ERROR:
java.text.ParseException: Unparseable date: "SA25MAY"
at java.text.DateFormat.parse(DateFormat.java:337)
at javadatatable.JavaDataTable.main(JavaDataTable.java:29)
Here I don't know how to resolve this problem.
ddd can not match SUN. Use EEE instead if you want to match the day name in the week.
You can only add one day if you know the year because of leap years (29th of February).
In case the year is the current year, the following solution should do the the job:
For "SA25MAY":
try {
String str_date = "SA25MAY";
// remove SA
str_date = str_date.replaceFirst("..", "");
// add current year
Calendar c = Calendar.getInstance();
str_date = c.get(Calendar.YEAR) + str_date;
// parse date
Date date;
SimpleDateFormat formatter = new SimpleDateFormat("yyyyddMMM");
date = formatter.parse(str_date);
System.out.println("Today is " + date);
// add day
c.setTime(date);
c.add(Calendar.DATE, 1);
// rebuild the old pattern with the new date
SimpleDateFormat formatter2 = new SimpleDateFormat("EEEddMMM");
String tomorrow = formatter2.format(c.getTime());
tomorrow = tomorrow.toUpperCase();
tomorrow = tomorrow.substring(0, 2) + tomorrow.substring(3);
System.out.println("Tomorrow is " + tomorrow);
} catch (Exception e) {
e.printStackTrace();
}
Or for "SA-25-MAY":
try {
String str_date = "SA-25-MAY";
// remove SA
str_date = str_date.replaceFirst("..-", "");
// add current year
Calendar c = Calendar.getInstance();
str_date = c.get(Calendar.YEAR) + "-" + str_date;
// parse date
Date date;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-dd-MMM");
date = formatter.parse(str_date);
System.out.println("Today is " + date);
// add day
c.setTime(date);
c.add(Calendar.DATE, 1);
// rebuild the old pattern with the new date
SimpleDateFormat formatter2 = new SimpleDateFormat("EEE-dd-MMM");
String tomorrow = formatter2.format(c.getTime());
tomorrow = tomorrow.toUpperCase();
tomorrow = tomorrow.substring(0, 2) + tomorrow.substring(3);
System.out.println("Tomorrow is " + tomorrow);
} catch (Exception e) {
e.printStackTrace();
}
I use a PostgreSQL database server. One column has "timestamp with time zone" and I upload time string through XML like '2012-07-11 04:45:18+GMT+05:30' but it accepts this format '2012-02-16 19:47:22.652+05:30'
So, how can I format the time string on Android? Below is my function.
Calendar c=Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ssZ");
Log.v("AKDN", "Time string is:"+formatter.format(c.getTime()));
return formatter.format(c.getTime());
This works fine for me:
private String getTime()
{
Calendar c = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SZ");
return formatter.format(c.getTime());
}
In my case it outputs:
2012-07-11 06:32:46.118-0600
EDIT:
You can either add the ":" to your string.
Or you can create another function to format the timezone. Something like this:
private String formatTimeZone(TimeZone tz)
{
DecimalFormat format = new DecimalFormat("00");
String timeZone = new String("");
int offset = tz.getRawOffset();
if(offset != 0)
{
int hours = Math.abs((offset / (60 * 1000)) / 60);
int minutes = Math.abs((offset / (60 * 1000)) % 60);
timeZone += offset < 0 ? "-" : "+";
timeZone += format.format(hours);
timeZone += ":";
timeZone += format.format(minutes);
}
return timeZone;
}
I have written a function for adding time in a 24 hour format as given below
for (int i = 0; i < cursor.getCount(); i++) {
String RevisedTime="00:00";
// 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);
}
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("kk:mm");
String date = sdf.format(calendar.getTime());
return date;
}
The problem is that while adding 15 minutes to 00:00 I am getting the output as 12.15....
I need to get it as 00:15......Pleas help me.....
You have to use 0-23 hour format, not 1-24.
Instead of SimpleDateFormat sdf = new SimpleDateFormat("kk:mm");
use SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
You just have to change a bit and it would work fine.
Replace
SimpleDateFormat sdf = new SimpleDateFormat("kk:mm");
By
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");