Round UTC date to nearest 5 minutes [duplicate] - java

This question already has answers here:
How to round time to the nearest quarter hour in java?
(17 answers)
Closed 8 years ago.
I have the following code to get datetime UTC.
public static Date GetUTCdatetimeAsDate()
{
return StringDateToDate(GetUTCdatetimeAsString());
}
public static String GetUTCdatetimeAsString()
{
final SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());
return utcTime;
}
public static Date StringDateToDate(String StrDate)
{
Date dateToReturn = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT);
try
{
dateToReturn = (Date)dateFormat.parse(StrDate);
}
catch (ParseException e)
{
e.printStackTrace();
}
return dateToReturn;
}
Now I want to use GETUTCdatetimeAsDate and if I get for example 11/22/2014 03:12 the minutes will be rounded up to the nearest 5 minutes. So in this case that will be 11/22/2014 03:15. If it is 11/22/2014 03:31 it will be 11/22/2014 03:35.
Any ideas on how to achieve this?

public static Date StringDateToDate(String StrDate) {
Date dateToReturn = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT);
try {
dateToReturn = (Date) dateFormat.parse(StrDate);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(dateToReturn);
int minute = c.get(Calendar.MINUTE);
minute = minute % 5;
if (minute != 0) {
int minuteToAdd = 5 - minute;
c.add(Calendar.MINUTE, minuteToAdd);
}
return c.getTime();
}

Related

how to highlights specific dates in CalendarView in android studio?

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

Public Function Not Returning Value

I am trying to calculate the difference between two dates but the function is not returning the value
I am calling the function like this
GeneralMethods generalMethods = new GeneralMethods();
generalMethods.daysPassed(contacts_update_date, currentDate);
And the function is as follows
public class GeneralMethods {
public long daysPassed(String contacts_update_date, String currentDate) {
// Calculate Time Passed
long diff;
long timePassed = 0;
SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = contacts_update_date;
String inputString2 = currentDate;
try {
Date date1 = myFormat.parse(inputString1);
Date date2 = myFormat.parse(inputString2);
diff = date2.getTime() - date1.getTime();
timePassed = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
} catch (ParseException e) {
e.printStackTrace();
}
return timePassed;
}
}
Finally I am using the value like this
if (timePassed > 30) {
//do something
}
Please try this
GeneralMethods generalMethods = new GeneralMethods();
long timePassed=generalMethods.daysPassed(contacts_update_date, currentDate);

Determinating if a given string time is in the past, using Java Calendar (Android) [duplicate]

This question already has answers here:
How to compare dates in Java? [duplicate]
(11 answers)
Closed 5 years ago.
I'm trying to write 'isPast(String dateStr)' function, which receives date string and returns true if it's in the past and false otherwise.
private static boolean isPast(String dateStr) {
Calendar c = GregorianCalendar.getInstance();
int currentYear = c.get(Calendar.YEAR);
int currentMonth = c.get(Calendar.MONTH);
int currentDay = c.get(Calendar.DAY_OF_MONTH);
int currentHour = c.get(Calendar.HOUR_OF_DAY);
int currentMinute = c.get(Calendar.MINUTE);
c.set(currentYear, currentMonth, currentDay, currentHour, currentMinute);
Date now = c.getTime();
SimpleDateFormat sdfDates = new SimpleDateFormat("dd/m/yyyy");
Date date = null;
try {
date = sdfDates.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
if (now.compareTo(date) == 1){
System.out.println(dateStr + " date given is past");
return true;
}
System.out.println(dateStr + " date given is future");
return false;
}
And i'm calling it with:
String str1 = "22/04/2018";
String str2 = "22/01/2018";
System.out.println(isPast(str1));
System.out.println(isPast(str2));
And the output is:
22/04/2018 date given is past
22/01/2018 date given is past
What is going on here? It's not true. I'm on this for too long - it should be simple, obviously i'm missing something with that Calendar object...
Use LocalDate that is available in Java 8
public static void main(String[] args) {
String str1 = "22/04/2018";
String str2 = "22/01/2018";
System.out.println(isPast(str1));
System.out.println(isPast(str2));
}
private static boolean isPast(String dateStr) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate dates = LocalDate.parse(dateStr, formatter);
return dates.isBefore(LocalDate.now());
}
Try this:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
private static final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
public static void main(String[] args) {
String str1 = "22/04/2018";
String str2 = "22/01/2018";
String str3 = "xx/01/2018";
Date now = new Date();
testDate (str1, now);
testDate (str2, now);
testDate (str3, now);
}
private static void testDate(String str, Date now) {
try {
if (sdf.parse(str).before(now)) {
System.out.println(str + " is in the past.");
} else {
System.out.println(str + " is in the future.");
}
} catch (ParseException e) {
System.out.println("Date not in format dd/MM/yyyy : " + str);
}
}
}
Output:
22/04/2018 is in the future.
22/01/2018 is in the past.
Date not in format dd/MM/yyyy : xx/01/2018
If you have to use Calendar, try this:
private static void testDateUsingCalendar (String str, Date now) {
try {
String[] split = str.split("/");
Calendar c = GregorianCalendar.getInstance();
c.set(Integer.valueOf(split[2]), Integer.valueOf(split[1]), Integer.valueOf(split[0]));
if (c.getTime().before(now)) {
System.out.println(str + " is in the past.");
} else {
System.out.println(str + " is in the future.");
}
} catch (Exception e) {
System.out.println("Date not in format dd/MM/yyyy : " + str);
}
}

adding date to calendar is not updating month [duplicate]

This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
Closed 6 years ago.
I'm working on an android application and new to it.
I have to get date from user and then add 28 days and store it in database.
This is what I have done so far
private void saveDate() throws ParseException {
DatabaseHelper db = new DatabaseHelper(ActivityPeriodToday.this.getActivity());
String pDate = periodDate.getText().toString().trim();
String pTime = periodTime.getText().toString().trim();
String next_expected = getNextExpected(pDate);
boolean isInserted = db.insertPeriodTodayIntoPeriods(pDate, pTime, early_late, pDifference, pType, next_expected);
if (isInserted == true) {
Toast.makeText(ActivityPeriodToday.this.getActivity(), "Saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ActivityPeriodToday.this.getActivity(), "Could not be saved", Toast.LENGTH_SHORT).show();
}
}
private String getNextExpected(String pDate) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(pDate));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DAY_OF_MONTH, 28);
return sdf.format(c.getTime());
}
But is code is not incrementing month.
Ex. If user selects 01/11/2016, then date is incremented and is saved
29/11/2016. But if user selects 16/11/2016 then saves date is
28/11/2016 but this should be 14/12/2016
Step 1
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dateInString));
Step-2 use add() to add number of days to calendar
c.add(Calendar.DATE, 40);
Try using this:
calendar.add(Calendar.DAY_OF_YEAR, 28);
Its Working for me.
Calendar c = Calendar.getInstance();
int Year = c.get(Calendar.YEAR);
int Month = c.get(Calendar.MONTH);
int Day = c.get(Calendar.DAY_OF_MONTH);
// current date
String CurrentDate = Year + "/" + Month + "/" + Day;
String dateInString = CurrentDate; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
c = Calendar.getInstance();
try {
c.setTime(sdf.parse(dateInString));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.add(Calendar.DATE, 28);//insert the number of days that you want
sdf = new SimpleDateFormat("dd/MM/yyyy");
Date resultdate = new Date(c.getTimeInMillis());
dateInString = sdf.format(resultdate);
Toast.makeText(MainActivity.this, ""+dateInString, Toast.LENGTH_SHORT).show();
Your question may already have an answer here: How can I increment a date by one day in Java?
Or you can simply use
c.add(Calendar.DATE, 28);
instead of
c.add(Calendar.DAY_OF_MONTH, 28);

How to get list of months & years between two dates

I need your help in getting the list of months and the years in String between two dates. The user will enter two dates in the String format of:
String date1 ="JAN-2015";
String date2 ="APR-2015";
So the result should be:
Jan-2015
FEB-2015
MAR-2015
I tried using the following code but it gave me wrong results:
List<Date> dates = new ArrayList<Date>();
String str_date ="JAN-2015";
String end_date ="APR-2015";
DateFormat formatter ;
formatter = new SimpleDateFormat("MMM-yyyy");
Date startDate = formatter.parse(str_date);
Date endDate = formatter.parse(end_date);
long endTime =endDate.getTime() ;
long curTime = startDate.getTime();
while (curTime <= endTime) {
dates.add(new Date(curTime));
curTime ++;
}
for(int i=0;i<dates.size();i++){
Date lDate =(Date)dates.get(i);
String ds = formatter.format(lDate);
System.out.println(ds);
}
Using the less code possible and basic java libraries and getting the result you asked for. So you can modify the date1 and date2 variables.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
String date1 = "JAN-2015";
String date2 = "APR-2015";
DateFormat formater = new SimpleDateFormat("MMM-yyyy");
Calendar beginCalendar = Calendar.getInstance();
Calendar finishCalendar = Calendar.getInstance();
try {
beginCalendar.setTime(formater.parse(date1));
finishCalendar.setTime(formater.parse(date2));
} catch (ParseException e) {
e.printStackTrace();
}
while (beginCalendar.before(finishCalendar)) {
// add one month to date per loop
String date = formater.format(beginCalendar.getTime()).toUpperCase();
System.out.println(date);
beginCalendar.add(Calendar.MONTH, 1);
}
}
}
In case your Java version is < 8 you could use Calendar as follows:
private final static DateFormat formatter = new SimpleDateFormat("MMM-yyyy", Locale.ENGLISH);
public static void main(String[] args) throws ParseException {
Calendar startDate = stringToCalendar("Jan-2015");
Calendar endDate = stringToCalendar("Apr-2015");
while (startDate.before(endDate)) {
System.out.println(formatter.format(startDate.getTime()));
startDate.add(Calendar.MONTH, 1);
}
}
private static Calendar stringToCalendar(String string) throws ParseException {
Date date = formatter.parse(string);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
If you have a luxury of Java 8 then the code becomes more simple:
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM-yyyy", Locale.ENGLISH);
YearMonth startDate = YearMonth.parse("Jan-2015", formatter);
YearMonth endDate = YearMonth.parse("Apr-2015", formatter);
while(startDate.isBefore(endDate)) {
System.out.println(startDate.format(formatter));
startDate = startDate.plusMonths(1);
}
}

Categories

Resources