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");
Related
i have tried most things online from custom calendar views to dependencies but they all lead to being outdated and not usable for android studio in its latest version.
does anyone know how to achieve this? I have tried mCalendarView, SunDeepK CalendarView and material-calendar view, but to no avail..
private void setCustomResourceForDates() {
Calendar cal = Calendar.getInstance();
//highlighlighting the holidays in a month taking the static dates
ArrayList<String> dates = new ArrayList<String>();
dates.add("02-08-2015");
dates.add("22-08-2015");
dates.add("17-09-2015");
dates.add("25-09-2015");
dates.add("27-09-2015");
dates.add("13-10-2015");
dates.add("22-10-2015");
SimpleDateFormat myFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
for (int i = 1; i < dates.size(); i++) {
inputString2 = dates.get(i);
inputString1 = myFormat.format(date);
try {
//Converting String format to date format
date1 = myFormat.parse(inputString1);
date2 = myFormat.parse(inputString2);
//Calculating number of days from two dates
long diff = date2.getTime() - date1.getTime();
long datee = diff / (1000 * 60 * 60 * 24);
//Converting long type to int type
day = (int) datee;
} catch (ParseException e) {
e.printStackTrace();
}
cal = Calendar.getInstance();
cal.add(Calendar.DATE, day);
holidayDay = cal.getTime();
colors();
}
}
public void colors() {
if (caldroidFragment != null) {
caldroidFragment.setBackgroundResourceForDate(R.color.green,
holidayDay);
caldroidFragment.setTextColorForDate(R.color.white, holidayDay);
}
}
}
call setCustomResourceForDates(); on onCreate method (in Caldroid Calendar
you can find it here : https://stackoverflow.com/a/32601769/20137896
I have Calendar value which is from Date Picker and I want to convert this value to String format "yyyy-MM-dd"
This is my Date Picker code. I save the selected values to startYear, startMonth and startDay.
ipDcEventStartDay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
DatePickerDialog dpd = new DatePickerDialog(DoubleCheckEventActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
startYear = year;
startMonth = month;
startDay = dayOfMonth;
ipDcEventStartDay.setText(startYear+ "-" + (startMonth+1) + "-" + startDay);
ipDcEventStartDay.setTextColor(Color.parseColor("#000000"));
}
}, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
dpd.show();
}
});
and then I tried to convert these values to String in this way. But the log result is 0002-12-31 not what I selected from Date Picker.
Calendar start = Calendar.getInstance();
start.set(startYear, startMonth, startDay);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = start.getTime(); // Convert to Date
String strStartDate = sdf.format(startDate); // Convert to String
Log.d("start", strStartDate); // this result is 0002-12-31
Never use Calendar. That terrible class was supplanted years ago by the modern java.time classes.
LocalDate
Instead, use LocalDate for a date-only value with no time-of-day and no offset or time zone.
LocalDate x = LocalDate.now() ;
String output = x.toString() ;
Build from parts.
LocalDate x = LocalDate.of( y , m , d ) ;
Get parts.
int y = x.getYear() ;
int m = x.getMonthValue() ;
int d = x.getDayOfMonth() ;
If your code goes like this; the log shows the date value before picking any dates. So you see the value for year: 0, month: 0 and day:0 (which is shown as 0002-12-31). (Note that the code inside onDateSet() method runs asynchronously, when the user picks a date.)
int startYear, startMonth, startDay;
Calendar today = GregorianCalendar.getInstance();
ipDcEventStartDay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
DatePickerDialog dpd = new DatePickerDialog(DoubleCheckEventActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
startYear = year;
startMonth = month;
startDay = dayOfMonth;
ipDcEventStartDay.setText(startYear+ "-" + (startMonth+1) + "-" + startDay);
ipDcEventStartDay.setTextColor(Color.parseColor("#000000"));
}
}, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
dpd.show();
}
});
// startYear, startMonth, startDay are not initialized yet and equal 0.
Calendar start = Calendar.getInstance();
start.set(startYear, startMonth, startDay);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = start.getTime(); // Convert to Date
String strStartDate = sdf.format(startDate); // Convert to String
Log.d("start", strStartDate); // this result is 0002-12-31
Instead; if you try to convert your Date to String "after the values are set" (Shown below) .You can see it will be correctly converted.
int startYear, startMonth, startDay;
Calendar today = GregorianCalendar.getInstance();
ipDcEventStartDay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
DatePickerDialog dpd = new DatePickerDialog(DoubleCheckEventActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
startYear = year;
startMonth = month;
startDay = dayOfMonth;
ipDcEventStartDay.setText(startYear+ "-" + (startMonth+1) + "-" + startDay);
ipDcEventStartDay.setTextColor(Color.parseColor("#000000"));
//************************************************************
//Now we have the picked values.
Calendar start = Calendar.getInstance();
start.set(startYear, startMonth, startDay);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = start.getTime(); // Convert to Date
String strStartDate = sdf.format(startDate); // Convert to String
Log.d("start", strStartDate); // this result is 0002-12-31
//************************************************************
}
}, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
dpd.show();
}
});
Let's see the simple code to convert Date to String
Basic
Date date = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
String strDate = dateFormat.format(date);
System.out.println("Converted String: " + strDate);
Advanced
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
String strDate = formatter.format(date);
System.out.println("Date Format with MM/dd/yyyy : "+strDate);
formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
strDate = formatter.format(date);
System.out.println("Date Format with dd-M-yyyy hh:mm:ss : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy zzzz");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy zzzz : "+strDate);
formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
strDate = formatter.format(date);
System.out.println("Date Format with E, dd MMM yyyy HH:mm:ss z : "+strDate);
}
I have a timestamp and I want to check whether the time is before or after a certain time (9:00 AM). To be more specific, I want to know whether a person is late or not and the cut-off time is 9 AM. How do I code this?
2015-09-22 08:59:59 //Print on time
2015-09-22 09:00:00 //Print on time
2015-09-22 09:00:01 //Print you are late
I think you can do like:
public static final String TIME_STAMP_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static void main(String[] args) {
Date standard = getStandardDate();
SimpleDateFormat format = new SimpleDateFormat(TIME_STAMP_FORMAT);
List<String> data = new ArrayList<String>();
data.add("2015-09-22 08:59:59");
data.add("2015-09-22 09:00:00");
data.add("2015-09-22 09:00:01");
for (String date : data) {
if(isLate(date, format)) {
System.out.println(date + " is Late");
} else {
System.out.println(date + " is On Time");
}
}
}
/**
* check is Late or not
* */
public static boolean isLate(String date, SimpleDateFormat format) {
Date standard = getStandardDate();
Date inputDate = null;
boolean result = false;
try {
inputDate = format.parse(date);
if(inputDate.after(standard)) {
result = true;
}
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
/**
* get standard date
* */
public static Date getStandardDate() {
Date dateNow = new Date ();
Calendar cal = Calendar.getInstance();
cal.setTime(dateNow);
cal.set(Calendar.DAY_OF_MONTH, 22);
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
Hope this help!
You can have code similar to following
// Get the provided date and time
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar providedDate = Calendar.getInstance();
providedDate.setTime(df.parse(stringInstanceRepresentingDate));
// Get the current date and time
Calendar cal = Calendar.getInstance();
// Set time of calendar to 09:00
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// Check if current time is after 09:00 today
boolean afterNine = providedDate.after(cal);
if (afterNine ) {
System.out.println("You are late");
}
else {
System.out.println("You are not late");
}
Assuming the input is a String, you can do the following
String input = ...;
String time = input.split(" ")[1],
hour = time.split(":")[0],
minute = time.split(":")[1],
seconds = time.split(":")[2];
if(Integer.parseInt(hour) > 9 && Integer.parseInt(minute) > 0) {
// Not on time
}
This is assuming the input is always perfect though, you should use try-catch blocks or check the input beforehand as this could throw exceptions.
LocalDateTime time = LocalDateTime.of(2015, 9, 22, 9, 0, 0);
LocalDateTime now = LocalDateTime.now();
if (now.compareTo(time) > 0)
System.out.println("You are late");
else System.out.println("You are in time");
If you are working with strings you have to split them first, as mentioned by #Deximus
I'm able to get current week dates, But How to list previous / next week days ?
This is the method
public String [] getWeekDay()
{
Calendar now = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
// System.out.println(Arrays.toString(days));
return days;
}
pls see the image, and tell me how to get the next and previous week days
finally i got the answer pls see this
Get the present Week:
public String [] getWeekDay()
{
Calendar now = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
return days;
}
Get the Next Week:
int weekDaysCount=0;
public String [] getWeekDayNext()
{
weekDaysCount++;
Calendar now1 = Calendar.getInstance();
Calendar now = (Calendar) now1.clone();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.WEEK_OF_YEAR , weekDaysCount);
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
return days;
}
Get the previous Week:
public String [] getWeekDayPrev()
{
weekDaysCount--;
Calendar now1 = Calendar.getInstance();
Calendar now = (Calendar) now1.clone();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.WEEK_OF_YEAR , weekDaysCount);
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
return days;
}
to assign the textView
NextPreWeekday = getWeekDay();
firstDayOfWeek = CommonMethod.convertWeekDays(NextPreWeekday [0]);
lastDayOfWeek = CommonMethod.convertWeekDays(NextPreWeekday [6]);
textViewDate.setText(firstDayOfWeek + "-" + lastDayOfWeek + " " + CommonMethod.convertWeekDaysMouth(NextPreWeekday [6]));
textViewSun.setText(CommonMethod.convertWeekDays(NextPreWeekday [0]) + "\nSun");
textViewMon.setText(CommonMethod.convertWeekDays(NextPreWeekday [1]) + "\nMon");
textViewTue.setText(CommonMethod.convertWeekDays(NextPreWeekday [2]) + "\nTue");
textViewWed.setText(CommonMethod.convertWeekDays(NextPreWeekday [3]) + "\nWeb");
textViewThu.setText(CommonMethod.convertWeekDays(NextPreWeekday [4]) + "\nThu");
textViewFri.setText(CommonMethod.convertWeekDays(NextPreWeekday [5]) + "\nFri");
textViewSat.setText(CommonMethod.convertWeekDays(NextPreWeekday [6]) + "\nSat");
public static String convertWeekDays(String date)
{
String formattedDate = null;
try
{
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd" , Locale.ENGLISH);
SimpleDateFormat targetFormat = new SimpleDateFormat("dd");
Date date12 = originalFormat.parse(date);
formattedDate = targetFormat.format(date12);
} catch (Exception e)
{
e.printStackTrace();
}
return formattedDate;
}
public static String convertWeekDaysMouth(String date)
{
String formattedDate = null;
try
{
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd" , Locale.ENGLISH);
SimpleDateFormat targetFormat = new SimpleDateFormat("MMM yyyy");
Date date12 = originalFormat.parse(date);
formattedDate = targetFormat.format(date12);
} catch (Exception e)
{
e.printStackTrace();
}
return formattedDate;
}
For current week.
SimpleDateFormat displayDate = new SimpleDateFormat("dd-MMM-yyyyy"));
final Calendar calenderThisWeek = Calendar.getInstance();
calenderThisWeek.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
String strWek = displayDate.format(calenderThisWeek.getTime()); // dd-mmm-yyyy
calenderThisWeek.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
String endWek = displayDate.format(calenderThisWeek.getTime()); // dd-mmm-yyyy
For Previous Week
final Calendar calenderpreviousWeek = Calendar.getInstance();
calenderpreviousWeek.add(Calendar.DAY_OF_WEEK, -1);
calenderpreviousWeek.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
String strWek = displayDate.format(calenderThisWeek.getTime()); // dd-mmm-yyyy
calenderpreviousWeek.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
String endWek = displayDate.format(calenderpreviousWeek.getTime()); // dd-mmm-yyyy
For Next Week
final Calendar calenderNextWeek = Calendar.getInstance();
calenderNextWeek.add(Calendar.DAY_OF_WEEK, +1);
calenderNextWeek.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
String strWek = displayDate.format(calenderNextWeek.getTime()); // dd-mmm-yyyy
calenderNextWeek.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
String endWek = displayDate.format(calenderNextWeek.getTime()); // dd-mmm-yyyy
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);