Display and save only hours in int - java

How to display only hours and using int variable? I mean print time like 20:30:44 PM, I want to store only hours, mean 20 in int variable. how to do that?
Can anybody tell me the code if you know, thanks?

Try using Calendar's get method like:
Calendar c = ..
c.setTime(...);//if you have time in long coming from somewhere else
int hour = c.get(Calendar.HOUR_OF_DAY);

If you try to parse time from String I recommend these solutions:
String time = "20:30:44 PM"; // this is your input string
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss aa");
try {
Date date = sdf.parse(time);
// this is the uglier solution
System.out.println("The hour is: "+date.getHours());
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
// this is nicer solution
System.out.println("The hour is: "+gc.get(Calendar.HOUR_OF_DAY));
} catch (ParseException e) {
System.err.println("Couldn't parse string! "+e.getMessage());
}
date.getHours() and gc.get(Calendar.HOUR_OF_DAY) return int, in this example I printed it out without creating variable.
You can, of course, use regular expression to find out hour in your string but above solutions should do the trick. You can learn more about SimpleDateFormat and available patterns here. I hope I helped you a bit.
EDIT: In his comment autor noted, that date isn't static (like in String) but dynamic:
Calendar calendar = new GregorianCalendar();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
System.out.println("The hour is: "+hour);
I hope this helps.

Related

Convert date to dd/MM/yyyy in Java

I am trying to get my calendar to print what day it is in dd/MM/yyyy format, but it just doesn't seem to work.
My code is:
SimpleDateFormat form = new SimpleDateFormat("dd/MM/yy", Locale.ENGLISH);
Date now = new Date("19/11/16");
form.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(form.format(now));
Calendar cal = Calendar.getInstance();
cal.setTime(now);
System.out.println(cal.get((Calendar.DAY_OF_WEEK)));
if(cal.get((Calendar.DAY_OF_WEEK)) < 7 || cal.get((Calendar.DAY_OF_WEEK)) > 1) {
System.out.println("It's a weekday");
}
else {
System.out.println("It's a weekend");
}
And the output is:
10/07/17
3
It's a weekday
Can anyone spot the issue?
The Date constructor you are calling is creating a Date with the wrong fields, to initialize your Date with your format parse the String. Like
Date now = form.parse("19/11/16");
Making sure to either catch (or rethrow) ParseException. With those two changes I then get
19/11/16
7
It's a weekday

SimpleDateFormat missing time

I have a strange issue. The below code is executed in a while loop through a few times. Now, every so often, this sdf.parse returns 0s for the hours, minutes and seconds. An example of the dates look like this...
2014:3:7:8:0
2014:3:7:9:0
2014:3:7:10:0
2014:3:7:11:0
2014:3:7:12:0 * This returns 0's
2014:3:7:13:0
2014:3:7:14:0
Below is the code.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:M:d:h:m");
sdf.setTimeZone(TimeZone.getDefault());
Date sTime = null;
try {
sTime = sdf.parse(start);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
I think 12 at hour position is getting read in 12h format, so it is the same as 0. Try H instead of h in pattern
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:M:d:H:m");
'h' represents hour in 1-12 format. You should use 'H' (in upper case) instead if you want 0-23 format. Also you needn't explicitly set default time zone because by default it equals TimeZone.getDefault().

Parsing time string and changing timezone

I am retrieving data from a webservice that provides a timestamp in the form of HH:mm:ss I am using SimpleDateFormat to convert this string into a date object then change its timezone if needed and also convert it from 24hour to 12 hour time.
Problem: When a time is fed in for 12am it looks like this 00:00:00
so 12:05 is 00:05:00
When i get the results they look like this.
times fed in 22:00:00 to 00:01:00
times retrieved 10:00 pm to 0:01 am
I have been looking around to see if there is a way to fix it but i feel like i will need to make a special case and parse the string myself if it has a 0 in the hours place.
Any help would be greatly appreciated.
public String parseTime(String time) {
String mTime = null;
TimeZone thisTimeZone = TimeZone.getDefault();
TimeZone ourTimeZone = TimeZone.getTimeZone("America/Los_Angeles");
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.US);
SimpleDateFormat sdfThisTimeZone = new SimpleDateFormat("K:mm:a",
Locale.getDefault());
Date date = null;
sdfThisTimeZone.setTimeZone(thisTimeZone);
sdf.setTimeZone(ourTimeZone);
try {
date = sdf.parse(time);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mTime = sdfThisTimeZone.format(date.getTime());
//**********************************New: Does Not Work********************************
DecimalFormat nft = new DecimalFormat("00"); mTime = nft.format(mTime);
//**********************************New **********************************************
return mTime;
}
I have tried the line using DecimalFormat but i just copied it into the code for now to see if it would work. Unfortunately it made my app crash. The code that i have posted is executed inside an Async Task so i am not sure if that makes any difference but still thankyou for your help. Eventually i will solve this. But for now it is such a small detail that only occurs for 1 hour at 12am that i am moving on to bigger issues. If anyone can shed some light on this that would be awesome.
String getConvertedDateTime (String dateTime) {
String convertedDateTime = dateTime;
if (convertedDateTime != null
&& !convertedDateTime.equalsIgnoreCase("")
&& !convertedDateTime.equalsIgnoreCase("null")) {
try {
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Calendar calendar = Calendar.getInstance();
java.util.Date convertedDate = formatter
.parse(convertedDateTime);
formatter.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
convertedDateTime = formatter.format(convertedDate.getTime());
} catch (Exception e) {
e.printStackTrace();
}
}
return convertedDateTime;
}

Issue with java DateFormat

Following is a piece of code that I am running.
#Test
public void testMyMehotd() {
String expected = "2012-09-12T20:13:47.796327Z";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'");
//df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date d = null;
try {
d = df.parse(expected);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
String actual = df.format(d);
System.out.println(expected);
System.out.println(actual);
}
but the output is different than what I expect.
expected : 2012-09-12T20:13:47.796327Z
actual : 2012-09-12T20:27:03.000327Z
Can someone tell me the reason for this and what is the solution.
Thanks in advance.
Whenever you exceed 999 milliseconds, DateFormat will try to add the remaining milliseconds to your date. Consider the following simpler example:
String expected = "2012-09-12T20:13:47.1001Z";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'");
Date d = df.parse(expected);
The resulting date will be 2012-09-12T20:13:48.0001. That is, since you have 1001 milliseconds, you get 1 extra second (1000 milliseconds), and 1 millisecond (1001 % 1000). Thus instead of 47 seconds as in the original date, you get 48 seconds.
This is also what happens if you try to parse a date with an invalid number of days in a month. For example, if you try to add an extra day to September, and parse 2012-09-31:
String expected = "2012-09-31";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date d = df.parse(expected);
System.out.println(df.format(d));
You'll actually get 2012-10-01. Again, that's because DateFormat will detect that the 31st day of September is not valid, and will try to use heuristics to transform the Date, thus adding one day, ending up with the first day of the next month.
There's an option to tell the parser not to use these heuristics, by setting lenient mode to false with:
df.setLenient(false);
However, using this mode, both above examples will throw a ParseException.
S means millisecond and you passed 796327 milliseconds. That number is equal to 13[min]:16[sec]:327[millis] so additional minutes and seconds ware added to your date.

convert a string of time to 24 hour format

I have a string holding a start time and an end time in this format 8:30AM - 9:30PM I want to be able to strip out the AM - and the PM and convert all the times to 24 hour format so 9:30PM would really be 21:30 and also have both the times stored in 2 different variables, I know how to strip the string into substrings but Im not sure about the conversion, this is what I have so far. the time variable starts out holding 8:30AM - 9:30PM.
String time = strLine.substring(85, 110).trim();
//time is "8:30AM - 9:30PM"
String startTime;
startTime = time.substring(0, 7).trim();
//startTime is "8:30AM"
String endTime;
endTime = time.substring(9).trim();
//endTime "9:30AM"
Working code (considering that you managed to split the Strings):
public class App {
public static void main(String[] args) {
try {
System.out.println(convertTo24HoursFormat("12:00AM")); // 00:00
System.out.println(convertTo24HoursFormat("12:00PM")); // 12:00
System.out.println(convertTo24HoursFormat("11:59PM")); // 23:59
System.out.println(convertTo24HoursFormat("9:30PM")); // 21:30
} catch (ParseException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Replace with KK:mma if you want 0-11 interval
private static final DateFormat TWELVE_TF = new SimpleDateFormat("hh:mma");
// Replace with kk:mm if you want 1-24 interval
private static final DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm");
public static String convertTo24HoursFormat(String twelveHourTime)
throws ParseException {
return TWENTY_FOUR_TF.format(
TWELVE_TF.parse(twelveHourTime));
}
}
Now that I think about it, SimpleDateFormat, H h K k can be confusing.
Cheers.
You need to use: SimpleDateFormat
And can refer this tutorial: Formatting hour using SimpleDateFormat
Example:
//create Date object
Date date = new Date();
//formatting hour in h (1-12 in AM/PM) format like 1, 2..12.
String strDateFormat = "h";
SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
System.out.println("hour in h format : " + sdf.format(date));
I wouldn't reinvent the wheel (unless you are doing this as a school project or some such).
Just get a date object out of your time stamp and then you can generate whatever format you want with this: SimpleDateFormat
[edited to address your specific request]
if you absolutely need to work from your own unique strings, then you'll do something like this (I don't know exactly what your strings look like... you're using offsets like 85, which means nothing out of context).
I didn't check this for bugs, but this is approximately what you want...
myStr = timestampString.toLowerCase(); //something like 8:30am
boolean add12 = (myStr.indexOf("pm") != -1)?true:false;
//convert hour to int
int hour = Integer.parseInt(myStr.split(":")[0]);
int minutes = Integer.parseInt( myStr.split(":")[1].replaceAll("\\D+","").replaceAll("^0+","") ); //get the letters out of the minute part and get a number out of that, also, strip out leading zeros
int militaryTime = hour + (add12)? 12:0;
if(!add12 && militaryTime == 12)
militaryTime = 0; //account for 12am
//dont' forget to add the leading zeros back in as you assemble your string
With Joda Time, the code looks like:
DateTimeFormatter formatter12 = DateTimeFormat.forPattern("K:mma");
DateTime begin = formatter12.parseDateTime(beginTime);
DateTime end = formatter12.parseDateTime(endTime);
DateTimeFormatter formatter24 = DateTimeFormat.forPattern("k:mma");
String begin24 = formatter24.print(begin);
String end24 = formatter24.print(end);
I should like to contribute the modern answer
DateTimeFormatter twelveHourFormatter = DateTimeFormatter.ofPattern("h:mma", Locale.ENGLISH);
String time = "8:30AM - 9:30PM";
String[] times = time.split(" - ");
LocalTime start = LocalTime.parse(times[0], twelveHourFormatter);
System.out.println(start.toString());
LocalTime end = LocalTime.parse(times[1], twelveHourFormatter);
System.out.println(end.toString());
This prints:
08:30
21:30
I am using java.time, the modern Java date and time API. The SimpleDateFormat class used in many of the other answers is long outdated and was always troublesome. java.time is so much nicer to work with than the date-time classes from the 1990’s. A LocalTime is a time of day without a date (and without time zone), so suits your need much better than an old-fashioned Date.
Link: Oracle tutorial: Date Time explaining how to use java.time.
24 hour time adds 12 to any time greater than 12pm so that 1pm is 13 and so on until 24 or 12am. Here is the sudo code:
if(hour <= 12)
{
hour = hour + 12;
}
All the below lines will works when
String str="07:05:45PM";
and when you call timeConversion(str) and want to convert to 24 hours format..
public class TimeConversion {
private static final DateFormat TWELVE_TF = new SimpleDateFormat("hh:mm:ssa");
private static final DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm:ss");
static String timeConversion(String s) {
String str = null;
try {
str= TWENTY_FOUR_TF.format(
TWELVE_TF.parse(s));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
public static void main(String[] args) throws ParseException {
String str="07:05:45PM";
System.out.println(timeConversion(str));
}
}

Categories