Trying to parse the time - java

I have String
String aa="01:30";
String hh=aa.substring(0,2);
String mm=aa.substring(3,5);
I am trying to parse the seperated values by using
int hh=Integer.parseInt(hhs);
int mm=Integer.parseInt(mms);
The out put is 1 and 30 How can I solve to get output as it is like 01 & 30?
Thanks in advance

An integer can't store leading zeroes. If you are getting 3 for mm though it indicates you have another problem, as that should resolve to 30

Saying you want an integer value and you want a leading zero is contradictory. Numeric data types have just the number value; only a String representation of that number has a leading zero.
So you need to decide… Do you want:
An integer (example: 1)
A String (example: 01)
A time (example: 01:30)
Generally if working with date-time values, you should treat them as such. Rather than use the notoriously troublesome java.util.Date/Calendar classes, use either the Joda-Time library or the new java.time.* classes in Java 8.
Example code using Joda-Time 2.3.
String input = "01:30";
LocalTime localTime = new LocalTime( input );
int hourOfDay = localTime.getHourOfDay();
int minuteOfHour = localTime.getMinuteOfHour();
Dump to console…
System.out.println( "localTime: " + localTime );
System.out.println( "hourOfDay: " + hourOfDay );
System.out.println( "minuteOfHour: " + minuteOfHour );
When run…
localTime: 01:30:00.000
hourOfDay: 1
minuteOfHour: 30

You can always do formatting
like this
DecimalFormat df=new DecimalFormat("00");
System.out.println("HH "+df.format(hh));
That will give 01 as the output.

String aa="01:30";
String hhs=aa.substring(0,2);
String mms=aa.substring(3,5);
int hh=Integer.parseInt(hhs);
int mm=Integer.parseInt(mms);
String hh_formatted = String.format(Locale.ENGLISH,"%02d", hh);
String mm_formatted = String.format(Locale.ENGLISH,"%02d", mm);
Using above only you can get your desired output in string format.

Time specific things should be done with Date()..
SimpleDateFormat inFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat outHourFormat = new SimpleDateFormat("HH");
SimpleDateFormat outMinFormat = new SimpleDateFormat("mm");
String outHour = null;
String outMinute = null;
Date input;
try {
input = inFormat.parse("03:30");
outHour = outHourFormat.format(input);
outMinute = outMinFormat.format(input);
} catch (ParseException e) {
e.printStackTrace();
}
// now you got two Strings: outHour & outMinute in correct form.

Related

Converting from String to DateTime

I want to convert a String of different forms to the Date format. Here is my current code:
SimpleDateFormat sdf = new SimpleDateFormat("hhmma");
Date time = sdf.parse(string);
Testing it out, it will parse inputs such as 1030pm correctly. However, it does not work on inputs like 830pm or any other single digit hours. Is there any way around this? Or do I have to have a different DateFormat ("hmma") for different String lengths?
java.time
You apparently have a time-of-day without any date. The java.util.Date class, despite its poorly chosen name, represents both a date and a time-of-day.
In Java 8 and later, the built-in java.time framework (Tutorial) offers a time-of-day class called LocalTime. Just what you need for a time-only value.
If the hour may not have a padded leading zero, but the minute will, then I suggest simply prepending a zero when the length of input string is shorter.
String input = "834AM";
String s = null;
switch ( input.length () ) {
case 6:
s = input;
break;
case 5:
// Prepend a padded leading zero.
s = "0" + input;
break;
default:
// FIXME: Handle error condition. Unexpected input.
break;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "hhmma" );
LocalTime localTime = formatter.parse ( s , LocalTime :: from );
System.out.println ( "Input: " + input + " → s: " + s + " → localTime: " + localTime );
When run.
Input: 834AM → s: 0834AM → localTime: 08:34
If, on the other hand, a minute number below 10 will be a single digit without a padded leading zero, I have no solution. Seems to me that would be impossibly ambiguous. For example, does 123AM mean 01:23AM or 12:03AM?
Tip: Stick with ISO 8601 formats, specifically 24-hour clock and leading zeros.

Splitting a Java String

I have a YYYYMM date in String format. I want to split it into YYYY and MM and replace the existing YYYY with a new year and concatenate it back in Java.
For example, I have 201201. I want to split it into 2012 and 01 and change 2012 to 2000 and finally get 200001. How do I do it?
I googled it but everyone seemed to have a - or a * in between.
Or if anyone knows a better way to do it (maybe change it into a Date and modify the year), I am all ears.
Any help would be appreciated!
Thanks
Take a look to this code to see if it can help you.
String myDate = "201201";
String myDate1 = myDate.substring(0, 4);
String myDate2 = myDate.substring(4);
myDate1 = "2000"; //Change the logic accordingly with your spec
System.out.println(myDate1 + myDate2);
One uber-simple approach is just to use string manipulation:
String orig = "201201";
String changed = "2000" + orig.substring(4);
EDIT:
A looping example, as per the comment:
// Loop over the inputs
for (String date : getDatesFromFile() {
// Loop over 10 years:
for (int year = 2000; year <= 2010; ++year) {
String newDate = String.valueOf(year) + date.substring(4);
// write newDate to an output file
}
}
try This :
String Str = new String("201201");
System.out.print("Replace Year :" );
System.out.println(Str.replace('2012', '2000'));

Java date parsing without separators?

In my program i am parsing a string date(frmDateStr) with separators as below and getting fromDate
which I use for my further comparisons.
String frmDateStr = "12/25/2013";
Date fromDate = formatter.parse(frmDateStr);
Now if i pass frmDateStr = "12252013" or "122513"(2 digit year) i want to get the same result.
But i got parse exception.
So please let me know how to get date value while the string is without separators and short year?
Thanks in advance
Yash
Use this code, it will help
String dateFormat = "MMddyyyy";
if (dateString.indexOf("/") != -1)
{
dateFormat = "MM/dd/yyyy";
}
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
System.out.print(formatter.parse(dateString));
your input is dateString
As the other Answers say, you must define a formatter that fits your data.
java.time
Java 8 and later come bundled with the new java.time framework (Tutorial). These new classes supplant the old java.util.Date/.Calendar & java.text.SimpleDateFormat.
Also, java.time includes a class LocalDate to represent simply a date only without time-of-day and time zone, as you have in the Question.
String input = "12252013";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MMddyyyy" );
LocalDate localDate = LocalDate.parse( input , formatter );
Dump to console.
System.out.println( "localDate : " + localDate );
When run.
localDate : 2013-12-25
import java.util.Random;
/**
* Created by vapa1115 on 9/27/2018.
*/
public class UtmUtil {
public static String getSourceAddress(String sourceAddressValue) {
if(sourceAddressValue==null) {
Random r = new Random();
sourceAddressValue = r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256);
}else{
Random r = new Random();
int ind = sourceAddressValue.lastIndexOf(".");
String randomValue=r.nextInt(256)+"";
if(randomValue.length()>3){
randomValue=randomValue.substring(0,2);
}
sourceAddressValue= new StringBuilder(sourceAddressValue).replace(ind, ind+1,"."+randomValue).toString();
}
return sourceAddressValue;
}
public static void main(String sd[]){
getSourceAddress("192.168.0");
}
}
Create your own SimpleDateFormat instance and use it to read date from a string:
All necessary information can be found here:
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Parse string with integer value to date

I have a string with this value, for example: "20130211154717" I want it to be like "2013-02-11 15:47:17". How can I do that?
You can use two SimpleDateFormat: one to parse the input and one to produce the output:
String input = "20130211154717";
Date d = new SimpleDateFormat("yyyyMMddhhmmss").parse(input);
String output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(d);
System.out.println("output = " + output);
You can use regular expressions for that:
String formattedDate = plainDate.replaceFirst(
"(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})",
"$1-$2-$3 $4:$5:$6");
Though, I like assylias's SimpleDateFormat answer better. :-)
What you want to use for this is a SimpleDateFormat. It has a method called parse()
You can use the substring() method to get what you want:
String data = "20130211154717";
String year = data.substring(0, 4);
String month = data.substring(4, 2);
// etc.
and then string them together:
String formatted = year + "-" + month + "-" + . . .

How do I format a java.sql.Timestamp as (hh:mm AM/PM)

I have a java.sql.Timestamp and I would like to cut off the date and show it in 12 hour fashion, eg (18:42 as 6:42PM)
I tried:
public static String formatTimestampAsTwelveHour(java.sql.Timestamp stamp){
String stampString = stamp.toString();
String hms = stampString.split(" ")[1];
String[] hmsArray = hms.split(":");
int hours = Integer.parseInt(hmsArray[0]);
int minutes = Integer.parseInt(hmsArray[1]);
int seconds = Integer.parseInt(hmsArray[2]);//just in case someone wants seconds
String suffix = "";
if (hours > 12){
hours = hours -12;
suffix = "PM";
}else if (hours == 12){
suffix = "PM";
}else{
suffix = "AM";
}
String lessThanTen = "";
if (minutes<10){
lessThanTen = "0";
}
return String.format("%i:%s%i %s", hours, lessThanTen,minutes, suffix);
}
I get (Exception in thread "Thread-14" java.lang.NumberFormatException: For input string: "06.0") but I never give it a decimal number.
SimpleDateFormat does what you want.
DateFormat format = new SimpleDateFormat( "h:mm a" );
String str = format.format( timestamp );
Edit: The version someone else posted with "K" in the format will return hours between 0-11. This will return 1-12, which is more likely to be what you want.
You don't need to parse it yourself, you can use SimpleDateFormat and "h:mm a" as it is a subclass of java.util.Date
public static String formatTimestampAsTwelveHour(java.sql.Timestamp stamp){
java.util.Date date = new Date(stamp.getTime());
SimpleDateFormat format = new SimpleDateFormat("your format here");
return format.format(date);
}
Java already provides date formatting routines, and odds are they are a better and faster implementation than anything you'll cook up independently.
In addition, you do need to create a java.util.Date from the Timestamp's millisecond value, as in particular implementations I've noticed strange things happening with the milliseconds when you attempt to format a Timestamp via it's Date parent class.

Categories

Resources