Issue in convert calendar object to date android - android

I want to convert calendar object to date as follow.
int year,month,day;
mCalendarEnd = Calendar.getInstance();
year = mCalendarEnd.get(Calendar.YEAR);
month = mCalendarEnd.get(Calendar.MONTH)+1;
day = mCalendarEnd.get(Calendar.DAY_OF_MONTH);
Now convert it to date object
Date d1 = new Date(day,month,year);
when I print date object:
System.out.println("Date : "+d1.getDay()+"/"+d1.getMonth()+"/"+d1.getYear());
it should print current date but in above code it prints the wrong date. Any idea how can I solve this problem? your all suggestion are appreciable.

You need to do it like this
//Set calendar
Calendar calendar = Calendar.getInstance();
Date date1 = calendar.getTime(); // gives a date object
//To get day difference, Just an example
calendar.add(Calendar.DAY_OF_MONTH, -7);
Date date2 = calendar.getTime(); // gives a date object
long differenceInMillis = Date1.getTime() - Date2.getTime();
long differenceInDays = TimeUnit.DAYS.convert(differenceInMillis, TimeUnit.MILLISECONDS);
Or No need of date objects
Calendar calendar = Calendar.getInstance();
long date1InMillis = calendar.getTimeInMillis();
calendar.add(Calendar.DAY_OF_MONTH, -7);
long date2InMillis = calendar.getTimeInMillis();
long differenceInMillis = date1InMillis - date2InMillis;
long differenceInDays = TimeUnit.DAYS.convert(differenceInMillis, TimeUnit.MILLISECONDS);
calendar.getTimeInMillis()

calendar.getTime() returns Date object.
but if you just need today date new Date() returns today date as Date object, too.
Calendar example:
Calendar calendar = Calendar.getInstance()
Log.i("My Tag", "calendar getTime -----> " + calendar.getTime());
Output:
My Tag: calendar getTime -----> Wed Dec 05 13:03:43 GMT+03:30 2018
Date Example:
Log.i("My Tag", "new Date -----> " + new Date());
Output:
My Tag: new Date -----> Wed Dec 05 13:05:38 GMT+03:30 2018
as you see both of them have the same output.

Why you don't use just the calendar?
System.out.println("Date : " + day + "/" + month + "/" + year);
result 1/1/1900
or you want other format? but dont increment the month with 1
System.out.println("Date : " + day + "/" + new DateFormatSymbols().getMonths()[month] + "/" + year);
result 1/January/1900

Put this in your code:
Date d1 = new Date(year, month, day);
System.out.println("Date : " + d1.getDate() + "/" +d1.getMonth() + "/" + d1.getYear());
you will get the correct date.

d1=new Date(year, month, day);
System.out.println("Dt:"+d1.getDate()+"/"+d1.getMonth()+"/"+d1.getYear());

Related

How to get current hour in android?

Time class is no longer possible to use.
I want to ask you, how to detect in app 3-4am?
I need that to set up for example night mode in my app.
Can you give me some example how to do it?
Instead of using Time (because Time class was deprecated in API level 22.) you can use Calendar for getting current hour
val rightNow = Calendar.getInstance()
val currentHourIn24Format: Int =rightNow.get(Calendar.HOUR_OF_DAY) // return the hour in 24 hrs format (ranging from 0-23)
val currentHourIn12Format: Int = rightNow.get(Calendar.HOUR) // return the hour in 12 hrs format (ranging from 0-11)
We can use the Calendar class to get a format like "HH:mm:ss"
Calendar calendar = Calendar.getInstance();
int hour24hrs = calendar.get(Calendar.HOUR_OF_DAY);
int hour12hrs = calendar.get(Calendar.HOUR);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
System.out.println("Current hour 24hrs format: " + hour24hrs + ":" + minutes +":"+ seconds);
System.out.println("Current hour 12hrs format: " + hour12hrs + ":" + minutes +":"+ seconds);
Other option using the Date class and applying the format "HH:mm:ss":
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
String dateformatted = dateFormat.format(date);
System.out.println(dateformatted);
You can use following methods:
SimpleDateFormat format = new SimpleDateFormat("HH", Locale.US);
String hour = format.format(new Date());
Calendar calendar = Calendar.getInstance();
int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);

Calendar.getInstance() returns 1-2-5(Day-Month-Year)

I have this chunk of code:
Calendar date1 = Calendar.getInstance();
DateTime dateTime1 = new DateTime(date1.YEAR, date1.MONTH, date1.DAY_OF_MONTH, date1.HOUR_OF_DAY, date1.MINUTE, date1.SECOND);
My problem is that date1 returns the date 01/02/0005 (in a 1/2/5 format). I read about SimpleDateFormat, however it returns the same value.
date1.YEAR returns only a constant value. The same value as Calendar.YEAR.
Instead, you need to use the date1.get(...) method, in conjunction with Calendar.YEAR. See this example:
Calendar date1 = Calendar.getInstance();
DateTime dateTime1 = new DateTime(date1.get(Calendar.YEAR), date1.get(Calendar.MONTH), date1.get(Calendar.DAY_OF_MONTH), date1.get(Calendar.HOUR_OF_DAY), date1.get(Calendar.MINUTE), date1.get(Calendar.SECOND);
Try these lines of code to get the correct date:-
Calendar ci = Calendar.getInstance();
String AM_PM;
if(ci.get(Calendar.AM_PM)==0)
{
AM_PM ="AM";
}
else
{
AM_PM ="PM";
}
String CiDateTime = "" + ci.get(Calendar.YEAR) + "-" +
(ci.get(Calendar.MONTH) + 1) + "-" +
ci.get(Calendar.DAY_OF_MONTH)+" "+AM_PM;
System.out.println("time=========================================="+CiDateTime);
For yours solution, try these
Calendar ci = Calendar.getInstance();
DateTime dateTime1 = new DateTime(ci.get(Calendar.YEAR), ci.get(Calendar.MONTH), ci.get(Calendar.DAY_OF_MONTH), ci.get(Calendar.HOUR_OF_DAY), ci.get(Calendar.MINUTE), ci.get(Calendar.SECOND);
Try below code:
Calendar date1 = Calendar.getInstance();
Date date = new Date();
date1.setTime(date);
DateTime dateTime1 = new DateTime(date1.YEAR, date1.MONTH, date1.DAY_OF_MONTH, date1.HOUR_OF_DAY, date1.MINUTE, date1.SECOND);

Date and time format in Android

How do you format correctly according to the device configuration a date and time when having year, month, day, hour and minute? for example I want to display 29 July, 2015, 10:30 Am, according to my time zone
You can use this method to format the datetime... u can replace new java.util.Date() with any datetime variable...
android.text.format.DateFormat df = new android.text.format.DateFormat();
df.format("dd-MMM-yyyy hh:mm aa", new java.util.Date());
String strDateTime = "29 July, 2015, 10:30 Am";
SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM, yyyy, hh:mm a");
strDateTime = sdf.format(Calendar.getInstance().getTime());
holder.txtTime.setText(strDateTime);
Please integrate the above code, that works fine for me.
Any help, do let me know.
Please Find the below solution
Calendar ci = Calendar.getInstance();
String AM_PM;
if(ci.get(Calendar.AM_PM)==0)
{
AM_PM ="AM";
}
else
{
AM_PM ="PM";
}
String CiDateTime = "" + ci.get(Calendar.DAY_OF_MONTH)+" "+
(ci.get(Calendar.MONTH) + 1)+","+
ci.get(Calendar.YEAR) + "-" +
+ "," +getCurrentTime()
+" "+AM_PM;
Call the method
private String getCurrentTime()
{
int hrsRight = 0;
Calendar c = Calendar.getInstance();
int hrs = c.get(Calendar.HOUR);
int min = c.get(Calendar.MINUTE);
if (hrs>12)
{
hrsRight = hrs - 12;
}
else
{
hrsRight = hrs;
}
return String.valueOf(hrsRight)+":"+String.valueOf(min);
}

Android how to customize date in listview

I want to show the date from current date on words in list view .How to customize that date.Could please any one tell me.For example when u booking ticket in railways it's showing the current date on-wards.Like that i want to implement.
![enter image description here][1]
[1]: http://i.stack.imgur.com/3NPXA.png
use the SimpleDateFormat for example
Date d = new Date();
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("c - LLLL");
String formattedDate = simpleDateFormat.format(d);//Mon - June for that format
Check the formats (yyyy,dd ...) in SimpleDateFormat
Hope this will help.
Code for checking date after or before today.
Calendar c = Calendar.getInstance();
// set the calendar to start of today
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
// and get that as a Date
Date today = c.getTime();
// or as a timestamp in milliseconds
long todayInMillis = c.getTimeInMillis();
// user-specified date which you are testing
// let's say the components come from a form or something
int year = 2011;
int month = 5;
int dayOfMonth = 20;
// reuse the calendar to set user specified date
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
// and get that as a Date
Date dateSpecified = c.getTime();
// test your condition
if (dateSpecified.before(today)) {
System.err.println("Date specified [" + dateSpecified + "] is before today [" + today + "]");
} else {
System.err.println("Date specified [" + dateSpecified + "] is NOT before today [" + today + "]");
}
Done

Get Date of past 7days from current in android

I am trying to fetch the date 7days prior to today's date.
I am using SimpleDateFormat to fetch today's date.
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
Please guide me through this
Updated answer which I found most useful
SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");
String currentDateandTime = sdf.format(new Date());
Date cdate=sdf.parse(currentDateandTime);
Calendar now2= Calendar.getInstance();
now2.add(Calendar.DATE, -7);
String beforedate=now2.get(Calendar.DATE)+"/"+(now2.get(Calendar.MONTH) + 1)+"/"+now2.get(Calendar.YEAR);
Date BeforeDate1=sdf.parse(beforedate);
cdate.compareTo(BeforeDate1);
Thank you for you reply
Use java.util.Calendar, set it to today's date and then subtract 7 days.
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DAY_OF_YEAR, -7);
Date 7daysBeforeDate = cal.getTime();
Edit: In Java 8 it can be done much easier by using classes from java.time package:
final LocalDate date = LocalDate.now();
final LocalDate dateMinus7Days = date.minusDays(7);
//Format and display date
final String formattedDate = dateMinus7Days.format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(formattedDate);
You can try out this,
import java.util.Calendar;
public class AddDaysToCurrentDate {
public static void main(String[] args) {
//create Calendar instance
Calendar now = Calendar.getInstance();
System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
//add days to current date using Calendar.add method
now.add(Calendar.DATE,1);
System.out.println("date after one day : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
//substract days from current date using Calendar.add method
now = Calendar.getInstance();
now.add(Calendar.DATE, -10);
System.out.println("date before 10 days : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
}
}
/*
Typical output would be
Current date : 12-25-2007
date after one day : 12-26-2007
date before 10 days : 12-15-2007
*/
Android get date before 7 days (one week)
Date myDate = dateFormat.parse(dateString);
And then either figure out how many milliseconds you need to subtract:
Date newDate = new Date(myDate.getTime() - 604800000L); // 7 * 24 * 60 * 60 * 1000
Or use the API provided by the java.util.Calendar class:
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date newDate = calendar.getTime();
Then, if you need to, convert it back to a String:
and finally
String date = dateFormat.format(newDate);
you can use this kotlin function to get any date before the current date.
/**
* get specific date before current date
* [day] number of day
* [month] number of month
* [year] number of year
* [count] number of day, month, year
*
* return date
*/
fun getBeforeDate(day: Boolean = false, month: Boolean = false, year: Boolean = false, count: Int = 0): String{
val currentCalendar = Calendar.getInstance()
val myFormat = "dd/MM/yyyy" // you can use your own date format
val sdf = SimpleDateFormat(myFormat, Locale.getDefault())
if (day){
currentCalendar.add(Calendar.DAY_OF_YEAR, -count)
}else if(month){
currentCalendar.add(Calendar.MONTH, -count)
}else if(year){
currentCalendar.add(Calendar.YEAR, -count)
}else{
// if user not provide any value then give current date
currentCalendar.add(Calendar.DAY_OF_YEAR, 0)
// or you can throw Exception
//throw Exception("Please provide at least one value")
}
return sdf.format(currentCalendar.time)
}
fun getBeforeDate(day: Boolean = false, month: Boolean = false, year: Boolean = false, count: Int = 0): String{
val currentCalendar = Calendar.getInstance()
val myFormat = "dd/MM/yyyy" // you can use your own date format
val sdf = SimpleDateFormat(myFormat, Locale.getDefault())
if (day){
currentCalendar.add(Calendar.DAY_OF_YEAR, -count)
}else if(month){
currentCalendar.add(Calendar.MONTH, -count)
}else if(year){
currentCalendar.add(Calendar.YEAR, -count)
}else{
// if user not provide any value then give current date
currentCalendar.add(Calendar.DAY_OF_YEAR, 0)
// or you can throw Exception
//throw Exception("Please provide at least one value")
}
return sdf.format(currentCalendar.time)
}

Categories

Resources