Set date and desired time in Android - java

I want to set date and time in my android app. The date should be today's date but the time should be set to 6:00 AM by default in the text field. I have read many links but most of them shows today's time and date (example: 2016-03-28 11:53:55).
String timetxt1 = "06:00:00";
Date datetxt1 = null;;
try {
datetxt1 = simpleDateFormat.parse(timetxt1);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar selectedDate1 = Calendar.getInstance();
selectedDate1.setTime(datetxt1);
edittxt.setText(dateFormatter.format(selectedDate1.getTime()));

Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 6);// for 6 hour
calendar.set(Calendar.MINUTE, 0);// for 0 min
calendar.set(Calendar.SECOND, 0);// for 0 sec
System.out.println(calendar.getTime());// print 'Mon Mar 28 06:00:00 ALMT 2016'

This was useful to me.
fun getFormattedDateTime(dateString: String):String{
var formattedDate=""
val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault())
val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
val calendar = Calendar.getInstance()
calendar.time = dateFormat.parse(dateString)!!
calendar[Calendar.HOUR_OF_DAY]=6
calendar[Calendar.MINUTE]=0
calendar[Calendar.SECOND]=0
formattedDate=sdf.format(calendar.time)
return formattedDate
}

To get current date use below method
public static String getCurrentDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
This will give you the current date alone. And if you want the time to be 6:00AM use the below method
public static String getCurrentDateAndTime6() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 6);
calendar.set(Calendar.MINUTE,0);
return dateFormat.format(calendar);
}

I've done like this,
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
date.setHours(6);
date.setMinutes(0);
date.setSeconds(0);
Log.d("DateTime", dateFormat.format(date));
OUTPUT : 2016/03/28 06:00:00

Related

Changing timezone of the date to UTC on API Level 21

I have a Date and I need to change timezone of this date to UTC. The code below does not work.
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.setTimeInMillis(dateLocal.getTime());
return new Date(cal.getTimeInMillis());
On the Stackoverflow all examples return either a String or use API 26. How can I solve my problem on the Android API 21?
Try this:
public Date getDateInUtc() {
String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
Date dateToReturn = null;
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
String utcTime = sdf.format(new Date());
try {
dateToReturn = dateFormat.parse(utcTime);
} catch (ParseException e) {
e.printStackTrace();
}
return dateToReturn;
}
Use cal.getTime(); which returns date
The same result you can get without SimpleDateFormat:
public Date dateInUtc(Date input) {
Calendar inputCalendar = Calendar.getInstance();
inputCalendar.setTime(input);
TimeZone timeZone = inputCalendar.getTimeZone();
long timeInUtc = input.getTime() - timeZone.getRawOffset();
Calendar outputCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
outputCalendar.setTimeInMillis(timeInUtc);
return outputCalendar.getTime();
}

How to set datetime to end of day in java

I want to set datetime of day as: startDate=2018/03/28 00:00:00 and endDate=2018/03/28 23:59:59
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
String str1=sdf1.format(cal.getTime());
String str2=sdf2.format(cal.getTime());
Date startDate = sdf1.parse(str1);
Date endDate = sdf2.parse(str2);
My problem:program is working and output endDate=2018/03/28 00:00:00
Would you please point out any mistakes to me in code?
update:
i used debug and it's working correct with
String str2=sdf2.format(cal.getTime());//2018-03-28 23:59:59
but when change string==>date is not correct with output 2018/03/28 00:00:00
If you want to initialize Date instances from a formatted string with both date and time then time codes should be added to the SimpleDateFormat pattern to parse strings in that format.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = sdf.parse("2018-03-28 00:00:00");
Date endDate = sdf.parse("2018-03-28 23:59:59");
If you want to simply set the hour, minute, and second on the current date then use a Calendar instance and set fields on it accordingly.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0)
Date startDate = cal.getTime();
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999)
Date endDate = cal.getTime();
And next output the Date in a particular format:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
System.out.println(sdf.format(startDate));
System.out.println(sdf.format(endDate));
Output:
2018/03/28 00:00:00
2018/03/28 23:59:59
Dealing with time zones
If time zone is other than the local time zone then it's a good idea to be explicit with what timezone you're working with. Calendar and SimpleDateFormat instances must be consistent with what timezone you're dealing with or the date and/or times may be off.
TimeZone utc = TimeZone.getTimeZone("UTC");
Calendar cal = Calendar.getInstance(utc);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
sdf.setTimeZone(utc);
A substitute for SimpleDateFormat is using DateTimeFormatter class found in the newer java.time package added to Java 8.
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str1=sdf1.format(cal.getTime());
String str2=sdf2.format(cal.getTime());
try {
Date startDate = sdf3.parse(str1);
Date endDate = sdf3.parse(str2);
System.out.println(str1);
System.out.println(str2);
System.out.println(startDate.toString());
System.out.println(endDate.toString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OUT PUT
2018-03-28 00:00:00
2018-03-28 23:59:59
Wed Mar 28 00:00:00 ICT 2018
Wed Mar 28 23:59:59 ICT 2018
I think, maybe sdf1 and sdf2 don't provide clear format.
So change time to HH:mm:ss.
If you just want to get the Date values for today's start and end times, you don't need to use date formatting utilities (like SimpleDateFormat) at all:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
Date startDate = cal.getTime();
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);
Date endDate = cal.getTime();
You can solve this problem like this
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
String str1=sdf1.format(cal.getTime());
String str2=sdf2.format(cal.getTime());
Date startDate = sdf1.parse(str1);
Date endDate = sdf2.parse(str2);
String startDateTime = sdf1.format(startDate);
String endDateTime = sdf2.format(endDate);
System.out.println("startDate ----->" + startDateTime);
System.out.println("endDate ----->" + endDateTime);
The output of this
startDate ----->2018-03-28 00:00:00
endDate ----->2018-03-28 23:59:59
Hope this is what you want.

Add a value to time

How to get system date and time.After getting time add 4hour to that time.Time Format is 12 Hour.I tried Like this
enter code here
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dataFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss a");
String strTime = dataFormat.format(calendar.getTime());
calendar.add(Calendar.HOUR_OF_DAY, 4);
Example:I given 10.30AM add 4hour.I need 2.30PM
Try this..
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR_OF_DAY, 4);
SimpleDateFormat dataFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
String strTime = dataFormat.format(calendar.getTime());

Java : How to parse date format to show specific output format?

In my app, i retrieve date from my database in a specific format. (Generated by PHP)
I would like to show a specific output in my Android app for this cases :
Input format from database : 2014-05-30 17:50:50
I would like to be able to show this format in a TexView :
if the date refers to today, i would like to show this format :
Today - 17h50
if the date refers to yesterday, i would to show this format :
Yesterday - 17h50
And for others days :
5 June - 17h50
How can i do that ?
[UPDATE]
String dateDebut = annonce.getDate_debut();
SimpleDateFormat inDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // inputFormat
SimpleDateFormat TodayDF = new SimpleDateFormat("HH'h'mm"); //OutputFormat For today and yesterday
SimpleDateFormat FullDF = new SimpleDateFormat("dd MMM - HH'h'mm"); //Outputformat long
Date inDate = null;
try {
inDate = inDF.parse(dateDebut);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//calendar for inputday
Calendar inCal = new GregorianCalendar();
inCal.setTime(inDate);
//startOfToday
Calendar cStartOfDate = new GregorianCalendar();
cStartOfDate.set(Calendar.HOUR, 0);
cStartOfDate.set(Calendar.MINUTE, 0);
cStartOfDate.set(Calendar.SECOND, 0);
cStartOfDate.set(Calendar.MILLISECOND, 0);
//endOfToday
Calendar cEndOfDate = new GregorianCalendar();
cEndOfDate.set(Calendar.HOUR, 23);
cEndOfDate.set(Calendar.MINUTE, 59);
cEndOfDate.set(Calendar.SECOND, 59);
//startOfYesterday
Calendar cStartOfYesterday = new GregorianCalendar();
cStartOfYesterday.set(Calendar.HOUR, 0);
cStartOfYesterday.set(Calendar.MINUTE, 0);
cStartOfYesterday.set(Calendar.SECOND, 0);
cStartOfYesterday.set(Calendar.MILLISECOND, 0);
//endOfYesterday
Calendar cEndOfYesterday = new GregorianCalendar();
cEndOfYesterday.set(Calendar.HOUR, 23);
cEndOfYesterday.set(Calendar.MINUTE, 59);
cEndOfYesterday.set(Calendar.SECOND, 59);
if (cStartOfDate.before(inCal) && cEndOfDate.after(inCal)){
System.out.println("Aujourd'hui - "+TodayDF.format(inDate));
viewHolder.dateDebut.setText("Aujourd'hui - "+TodayDF.format(inDate));
} else if (cStartOfYesterday.before(inCal) && cEndOfYesterday.after(inCal)){
System.out.println("Hier - "+TodayDF.format(inDate));
viewHolder.dateDebut.setText("Hier - "+TodayDF.format(inDate));
} else {
System.out.println(FullDF.format(inDate));
viewHolder.dateDebut.setText(FullDF.format(inDate));
}
Try out this Code:
DateFormat inDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // inputFormat
DateFormat TodayDF = new SimpleDateFormat("HH'h'mm"); //OutputFormat For today and yesterday
DateFormat FullDF = new SimpleDateFormat("dd MMM - HH'h'mm"); //Outputformat long
Date inDate = inDF.parse("2014-06-05 17:50:50");
//calendar for inputday
Calendar inCal = new GregorianCalendar();
inCal.setTime(inDate);
//startOfToday
Calendar cStartOfDate = new GregorianCalendar();
cStartOfDate.set(Calendar.HOUR_OF_DAY, 0);
cStartOfDate.set(Calendar.MINUTE, 0);
cStartOfDate.set(Calendar.SECOND, 0);
cStartOfDate.set(Calendar.MILLISECOND, 0);
//endOfToday
Calendar cEndOfDate = new GregorianCalendar();
cEndOfDate.set(Calendar.HOUR_OF_DAY, 23);
cEndOfDate.set(Calendar.MINUTE, 59);
cEndOfDate.set(Calendar.SECOND, 59);
//startOfYesterday
Calendar cStartOfYesterday = new GregorianCalendar();
cStartOfYesterday.set(Calendar.HOUR_OF_DAY, 0);
cStartOfYesterday.set(Calendar.MINUTE, 0);
cStartOfYesterday.set(Calendar.SECOND, 0);
cStartOfYesterday.set(Calendar.MILLISECOND, 0);
//endOfYesterday
Calendar cEndOfYesterday = new GregorianCalendar();
cEndOfYesterday.set(Calendar.HOUR_OF_DAY, 23);
cEndOfYesterday.set(Calendar.MINUTE, 59);
cEndOfYesterday.set(Calendar.SECOND, 59);
if (cStartOfDate.before(inCal) && cEndOfDate.after(inCal)){
System.out.println("Today "+TodayDF.format(inDate));
} else if (cStartOfYesterday.before(inCal) && cEndOfYesterday.after(inCal)){
System.out.println("Yesterday"+TodayDF.format(inDate));
} else {
System.out.println(FullDF.format(inDate));
}
First convert the date obtained from database to a Calendar instance
Today and Yesterday can be identified with the Calendar instance
For the other formats use below:
Code:
Calendar cal = Calendar.getInstance();
new SimpleDateFormat("dd MMMM - HH").format(cal.getTime())+
"h" + new SimpleDateFormat("mm").format(cal.getTime())
Here is a complete solution. I did not try it, but it should work.
NB: Be carefull about input limits: I am not sure it will work if the date is 01/01/2015 for example. I let you test this.
private boolean checkSameDate(Calendar cal1, Calendar cal2) {
if ((cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR))
&& (cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR))) {
return true;
}
return false;
}
private void checkDate(Date date) {
Calendar cal = new GregorianCalendar();
cal.setTime(new Date());
Calendar cal2 = new GregorianCalendar();
cal2.setTime(date);
cal.add(Calendar.DAY_OF_YEAR, 1);
if (checkSameDate(cal, cal2)) {
// Your input date is tomorrow.
} else {
cal.add(Calendar.DAY_OF_YEAR, -2);
if (checkSameDate(cal, cal2)) {
// Your input date is yesterday.
} else {
DateFormat sdf = new SimpleDateFormat("dd MMMM - HH:mm");
System.out.println(sdf.format(date));
}
}
}
Edit
Sorry, I think it will not work for a date in 31/12/YYYY-1 when today is 01/01/YYYY. Maybe you can fix this code with this kind of solution: Check if one date is exactly 24 hours or more after another
For SimpleDateFormat, I let you check here https://ideone.com/dsxKN9 if this is the format you need.
Edit 2
I just see that you want today and not tomorrow :). My bad! I'll try fix this, but if you understand the logical, you'll be able to do it.
You can do it in using this function:
public static String convertDate(String stringDate, String oldFormat) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(oldFormat);
Date date = sdf.parse(stringDate);
double daysAgo = (System.currentTimeMillis() - date.getTime()) / (24 * 60 * 60 * 1000d);
System.out.println(daysAgo);
String newFormat;
if (daysAgo<=0){
newFormat="'Today -' HH'h'mm";
}
else if (daysAgo>=0 && daysAgo<=1){
newFormat="'Yesterday -' HH'h'mm";
}
else {
newFormat="d MMMM '-' HH'h'mm";
}
sdf.applyPattern(newFormat);
return sdf.format(date);
}
And the usage would be:
String newDate = convertDate("2014-06-03 17:50:50", "yyyy-MM-dd HH:mm:ss");

How to parse "dd-MM" date format to get current year?"

I have to parse "17-Jun" format date using Java.But the problem is when I try to parse "dd-MM" format using SimpleDateFormat it is returning as "Wed Jun 17 00:00:00 IST 1970".Is it possible to get current(2014) year instead of 1970.
My result:
17/JUNE/1970
Expected result:
17/JUNE/2014
Have a look at this..
Calendar c = Calendar.getInstance();
c.set(Calendar.DATE, 17);
c.set(Calendar.MONTH, 5);
c.set(Calendar.YEAR, c.get(Calendar.YEAR));
Date date=new Date(c.getTimeInMillis());
SimpleDateFormat simpleDateformatter = new SimpleDateFormat("dd/mmm/yyyy");
String convertedDate = simpleDateformatter .format(date);
To get year you can just use
Calendar cal = Calendar.getInstance();
cal.get(Calendar.YEAR) will fetch you current year
Hope it helped... :)
Try this
Calendar c = Calendar.getInstance();
c.set(Calendar.DATE, 17);
c.set(Calendar.MONTH, 5);
c.set(Calendar.YEAR, c.get(Calendar.YEAR));
Date d=new Date(c.getTimeInMillis());
SimpleDateFormat formatter = new SimpleDateFormat("dd- mmm");
String conDate = formatter.format(d);
Do like this
Date date = new SimpleDateFormat("dd-MMM-yyyy").parse("17-Jun-"+ Calendar.getInstance().get(Calendar.YEAR));
You'll have to write a utility method, there isn't anything in SimpleDateFormat that will interpret a non-existant year as the current year. Something like this:
public static Date parseDate(String dateString) throws ParseException {
//determine current year
Calendar today = Calendar.getInstance();
int currentYear = today.get(Calendar.YEAR);
//parse input
SimpleDateFormat format = new SimpleDateFormat("dd-MMM");
Date parsed = format.parse(dateString);
// set current year on parsed value
Calendar cal = Calendar.getInstance();
cal.setTime(parsed);
cal.set(Calendar.YEAR, currentYear);
return cal.getTime();
}
Try this:
SimpleDateFormat dfDate = new SimpleDateFormat("dd-MM-yyyy");
java.util.Date d = null;
try {
d = dfDate.parse("17-Jun-"+ Calendar.getInstance().get(Calendar.YEAR));
} catch (java.text.ParseException e) {
e.printStackTrace();
}
System.out.println(""+d );
your problem will be solved.
java.time
In Java 8 you can do something like:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("d-MMM");
MonthDay md = MonthDay.parse("17-Jun", dtf);
LocalDate d = LocalDate.now().with(md);
System.out.println(d.getDayOfMonth());
System.out.println(d.getMonthValue());
System.out.println(d.getYear());
I guess the simplest way is to do this:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MMM/dd");
Date date = new Date();
System.out.println("Time is: " + dateFormat.format(date) );
This gives you exactly what you want. also see
http://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html
Little late, but if you really don't want to use Calendar at all - as I gather from your comments to the correct answers above - (not recommended with the usage of deprecated methods, but still):
SimpleDateFormat format = new SimpleDateFormat("dd-MMM");
Date date = format.parse("17-JUN");
date.setYear(new Date().getYear());
System.out.println(date);
Output:
Tue Jun 17 00:00:00 IST 2014
All answers given here are more or less correct, but I notice that one detail aspect is still overlooked, namely if the combination of day and months fits to current year (february 29 problem). So I would suggest a strict parsing like following:
String ddMMM = "17-Jun";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
sdf.setLenient(false); // in order to check for "29-Feb"
TimeZone tz = TimeZone.getDefault(); // or change to your specific time zone
Date date =
sdf.parse(ddMMM + "-" + new GregorianCalendar(tz).get(Calendar.YEAR));
Try,
String s2 = "Wed Jun 17 00:00:00 1970";
SimpleDateFormat sdf1 = new SimpleDateFormat("E MMM dd hh:mm:ss yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MMM/yyyy");
try {
Date d1 = sdf1.parse(s2);
System.out.println(d1);
String s3 = sdf2.format(d1);
System.out.println("Before Changing :: "+s3);
Calendar cal = Calendar.getInstance();
cal.setTime(d1);
cal.add(Calendar.YEAR, 2014-1970);
d1 = cal.getTime();
String s4 = sdf2.format(d1);
System.out.println("After Changing :: "+s4);
} catch (ParseException e) {
e.printStackTrace();
}
Output
Before Changing :: 17/Jun/1970
After Changing :: 17/Jun/2014

Categories

Resources