set time to 00:00:00 doesn't work - java - java

I want to set string that contain the new current date and the time 00:00:00.
I wrote the following code but time is set to 12:00:00
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
String today1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").
format(calendar.getTime())
I'd love to know why the code does not work or, alternatively, get another method to set time to 00:00:00

You've used the format characters hh, which is the 12-hour, or am/pm, based hour scheme.
h Hour in am/pm (1-12) Number 12
You've printed 12:00 am without the "am". The time of day is set to midnight, but with your format "yyyy-MM-dd hh:mm:ss" the output is confusing at best.
You can do either of the following:
Switch to capital "H" characters to switch to a 24-hour clock as per your requirements:
H Hour in day (0-23) Number 0
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
Output:
2016-02-18 00:00:00
Or you can add the "a" format character to add the am/pm designation.
a Am/pm marker Text PM
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a")
Output:
2016-02-18 12:00:00 AM

Related

Date object that gets the current date, but with a time i control which can be converted to unix time

I want to be able to request java to get the current date, then I would like to control the time added to that date object and then convert that date object to unix time.
i.e. something like
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
Then do this using the Calendar object as a converted string
String dateString = "Fri, 09 Nov 2012 23:40:18 GMT"; //but this
DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy
hh:mm:ssz");
Date date = dateFormat.parse(dateString );
long unixTime = (long) date.getTime()/1000;
System.out.println(unixTime );
Any help would be appreciated.
First of all, there are some issues with your date format: You have to use capital H for hours when parsing 24-hour times, and I think there was a space missing in front of the timezone z.
Using the newer Java time API, you can try this:
ZonedDateTime.parse("Fri, 09 Nov 2012 23:40:18 GMT", DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z"))
.with(LocalDate.now())
.toEpochSecond();
The new API is very strict when it come to timezones, you might want to watch out for that. In this implementation, the parsed time defines the timezone (GMT in this example). But maybe you want your local timezone (defined by the virtual machine)? In this case, you can turn it around: ZonedDateTime.now().with(ZonedDateTime.parse(...).toLocalTime()).
In your original approach, why do you not continue with the Calendar?
Date parsedDate = ...;
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, parsedDate.getHours());
today.set(Calendar.MINUTE, parsedDate.getMinutes());
today.set(Calendar.SECOND, parsedDate.getSeconds());
today.set(Calendar.MILLISECOND, 0);
long epoch = today.getTimeInMillis() / 1000;
But again, beware of timezones.

Not able to properly display time in AM, PM format in Android

I have achieved time formate using AM-PM by below code
Date date = new SimpleDateFormat("h:m").parse((mHour+":"+mMinute));
String newString = new SimpleDateFormat("hh:mm a").format(date);
System.out.println("Time - "+newString);
but in above code there is one problem
If I set time 12:00 AM in TimePickerDialog it will display 12:00 AM but if I change time in TimePickerDialog to 12:00 PM it will still display 12:00 AM
It's because h is for 12 hour time format. And your TimePickerDialog is sending you a 24 hour format.
Use,
Date date = new SimpleDateFormat("H:m").parse((mHour+":"+mMinute)); // Upper H here.
EDIT:
SimpleDateFormat java doc, Check out the Date and Time Patterns section.
hh which is the 1-12 hour format. Try using capital HH, which uses 0-23 format.
" HH:mm"
so use
Date date = new SimpleDateFormat("HH:mm").parse((mHour+":"+mMinute));

How to convert "12-JAN-15 03.51.22.638000000 AM" in java?

I have a date in the format "12-JAN-15 03.51.22.638000000 AM".
I want it to convert to "12-01-15 00:00:00.000"
Even though there are hours,minuts and secs etc,i want the output with zeros only.
You want to convert one date format to another. This answer does exactly that. It states
DateFormat originalFormat = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("yyyyMMdd");
Date date = originalFormat.parse("August 21, 2012");
String formattedDate = targetFormat.format(date); // 20120821
In your case the original and target format are as follow
Original format: dd-MMM-yy hh.mm.ss.N a
Target format: dd-MM-yy hh:mm:ss:S
I am not sure how to replace the time data with 0. Perhaps a string manipulation is the way to go in your case. But if you want more control then you can do something like this.
Calendar cal = Calendar.getInstance();
cal.setTime(date); // this is the date we parsed above
cal.set(Calendar.HOUR_OF_DAY,0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
formattedDate = targetFormat.format(cal.getTime());
EDIT
# Sufiyan Ghori has provided a more cleaner way to do it.
Using Java 8,
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("MM-dd-yy:hh:mm:ss:nn"); // n = nano-of-second
LocalDateTime today = LocalDateTime.of(LocalDate.of(2015, 1, 15),
LocalTime.of(00, 00, 00, 00));
System.out.println(today.format(formatter));
Output
01-15-15:12:00:00:00
Explanation,
LocalDateTime.of(LocalDate.of(int Year, int Month, int Day),
LocalTime.of(int Hour, int Minutes, int Seconds, int nanoOfSeconds));
String string = "January 2, 2010";
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date); // Sat Jan 02 00:00:00 GMT 2010
You can follow to this javadoc, listing all available format patterns:
G Era designator Text AD
y Year Year 1996; 96
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day in week Text Tuesday; Tue
u Day number of week Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT- 08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
You can refer to this answer for detailed explanation.
String dateInString = "12-JAN-15 10.17.07.107000000 AM";
dateInString = dateInString.substring(0, 9);
Date date = null;
try {
date = new SimpleDateFormat("dd-MMM-yy", Locale.ENGLISH).parse(dateInString);
} catch (ParseException e) {
e.printStackTrace();
}
String newFormat = new SimpleDateFormat("dd-MM-yy 00:00:00.000").format(date);
System.out.println(newFormat);

How to format date for use in a URL as a parameter

I am using an API to get a weather forecast up until a particular date in Java.
The requirement for passing a date as a URL parameter is that it must be in "YYYY-MM-DD'T'HH:MM:SS" format. I get input in this format from the user, then get the current system date, and then loop until the desired date. The problem lies in converting the input date string into the date format, incrementing it by one day, and then converting it back to the string format for URL parameter.
I am using the following code to do this but it is giving me incorrect results:
formatter = new SimpleDateFormat("YYYY-MM-DD'T'HH:MM:SS");
Date date1 = formatter.parse(inputtime);
System.out.println(date1);
Calendar c1 = Calendar.getInstance();
c1.setTime(date1);
c1.add(Calendar.DAY_OF_MONTH, 1); // number of days to add
inputtime = formatter.format(c1.getTime()); // dt is now the new date
System.out.println(c1.getTime());
System.out.println(inputtime);
inputtime is the input by the user. If I give "2014-04-12T00:00:00" as inputtime, date1 is then "Sun Dec 29 00:00:00 PKT 2013", c1.getTime() returns "Mon Dec 30 00:00:00 PKT 2013" and inputtime becomes then "2014-12-364T00:12:00" according to the above code block.
How can this logic error be corrected?
You should consider SimpleDateFormat date and time patterns: link
For example, something like this:
formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Have a try to change your date pattern from
new SimpleDateFormat("YYYY-MM-DD'T'HH:MM:SS");
to
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Letter Date or Time Component Presentation Examples
y Year Year 1996; 96
M Month in year Month July; Jul; 07
D Day in year Number 189
d Day in month Number 10
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them.
That format is defined by the ISO 8601 standard. The Joda-Time library follows that standard's formats as a default for both parsing and generating strings. So does the new java.time package in Java 8.
Your string omits a time zone offset. So, you need to know and specify the time zone intended by that string. Perhaps the time zone is UTC meaning a time zone offset of zero.
A day is not always 24 hours. If you meant 24 hours rather than 1 day, call the method plusHours( 24 ).
Here is example code in Joda-Time 2.3.
String input = "2014-01-02T03:04:05";
DateTimeZone timeZone = DateTimeZone.UTC;
DateTime dateTime = new DateTime( input, timeZone );
DateTime tomorrow = dateTime.plusDays( 1 );
String outputWithOffset = tomorrow.toString();
String output = ISODateTimeFormat.dateHourMinuteSecond().print( tomorrow );

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());

Categories

Resources