How to set datetime to end of day in java - 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.

Related

String to timestamp Android

I have the following string:
19 July 2016 at 07:00:00 UTC
and am using the below code to convert it to a timestamp. However the console is throwing the following error:
java.text.ParseException: Unparseable date: "19 July 2016 at 07:00:00 UTC" (at offset 2)
CODE:
String time = todayAt7;
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
try {
Date date = sdf.parse(time);
System.out.println("Date and Time: " + date);
} catch (Exception e1) {
e1.printStackTrace();
}
Essentially I am trying to figure out the timestamp for 'today at 7am', is there a way to do this that I am missing?
In your code DateFormat sdf = new SimpleDateFormat("hh:mm:ss"); is not correct. The string argument should match the format of the date string your are trying to parse
try below
DateFormat sdf = new SimpleDateFormat("dd mmmm yyyy 'at' HH:mm:ss z");
If you want timestamp at today 7 AM, you can try the below
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 7);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(cal.getTime());
Output:
Tue Jul 19 07:00:00 EDT 2016

Set date and desired time in Android

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

Strange java.util.calendar Output

I am trying to clear the time portion from a Date using Java Calendar. Here is the code based on the other stackoverflow solutions:
Calendar cal = Calendar.getInstance();
// cal.setTime(new Date());
cal.clear(Calendar.HOUR);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
// cal.clear(Calendar.ZONE_OFFSET);
cal.clear(Calendar.HOUR_OF_DAY);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dateFormat.format(cal.getTime());
System.out.println(dateFormat.format(cal.getTime()));
System.out.println(cal.getTime());
But the current output is: 2014-01-20 12:00:00
What could be the reason? Why the time is showing 12:00:00? I just want my Date Object with a time 00:00:00.
The date/calendar is ok, the error is in your format string:
hh: means 12h time format
HH: means 24h time format
Correct format string:
yyyy-MM-dd HH:mm:ss
Output:
2014-01-20 00:00:00
Mon Jan 20 00:00:00 CET 2014
As per javadoc of Calendar.clear:
The HOUR_OF_DAY, HOUR and AM_PM fields are handled independently and
the the resolution rule for the time of day is applied. Clearing one
of the fields doesn't reset the hour of day value of this Calendar.
Use set(Calendar.HOUR_OF_DAY, 0) to reset the hour value.
So instead of clear use:
cal.set(Calendar.HOUR_OF_DAY, 0)
clear isn't actually clearing hour value, hence so much messing around formatters!
Do like this
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);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dateFormat.format(cal.getTime());
System.out.println(dateFormat.format(cal.getTime()));
System.out.println(cal.getTime());

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

Possible to remove the time and just want the date from getTime() Date class?

Is it possible to remove the day (Fri), the time (22:34:21) and the time zone (GMT) by just having an output like "Jan 11 1980" instead of "Fri Jan 11 22:34:21 GMT 1980"??
Code below:
Calendar date = Calendar.getInstance();
date.set(Calendar.YEAR, 1980);
date.set(Calendar.MONTH, 0);
date.set(Calendar.DAY_OF_MONTH, 11);
Date dob = date.getTime();
System.out.println(dob);//Fri Jan 11 22:34:21 GMT 1980
Many thanks!
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy");
System.out.println(sdf.format(date));
Output:
Feb 26 2013
If you want a specific date, do
Calendar c = Calendar.getInstance();
c.set(1980, 0, 11);
Date date = c.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy");
System.out.println(sdf.format(date));
Prints
Jan 11 1980
public class DateFormat {
public static void main(String[] args) {
Calendar date = Calendar.getInstance();
date.set(Calendar.YEAR, 1980);
date.set(Calendar.MONTH, 0);
date.set(Calendar.DAY_OF_MONTH, 11);
Date dob = date.getTime();
System.out.println(new SimpleDateFormat("MMM dd yyyy").format(dob));
}
}
Output:
Jan 11 1980
Date is a representation of the number of milliseconds since the epoch (January 1, 1970, 00:00:00 GMT)
In order to "remove" the time portion of a Date, you will want to use a DateFormat
Something as simple as;
System.out.println(new SimpleDateFormat("dd/MM/yyyy").format(dob));
Should work.
For a more localised version, you should use DateFormat.getDateInstance()
System.out.println(DateFormat.getDateInstance().format(dob));
System.out.println(DateFormat.getDateInstance(DateFormat.SHORT).format(dob));
System.out.println(DateFormat.getDateInstance(DateFormat.MEDIUM).format(dob));
System.out.println(DateFormat.getDateInstance(DateFormat.LONG).format(dob));
DateFormat dateFormatter = DateFormat.getDateInstance();
System.out.println(dateFormatter.format(date);
This will print the only the date corresponding to your current system locale settings.
See also: DateFormat in the JavaDoc
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy");
System.out.println(sdf.format(dob));
you can use:
stringToPrint = time.getMonth()+" "+time.getDate()+" "+time.getYear();
for more info:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.html

Categories

Resources