limiting the length of a string - java

I have a string that says 15:00:00 how can I limit the length of the string so it says 15:00 ?

For dates
Date date = new Date();
SimpleDateFormat sd = new SimpleDateFormat("HH:mm");
sd.format(date); //will return formatted date

Try this,
String time = "15:00:00";
time = time.subString(0,time.lastIndexOf(":"));

try this:
String time = "15:00:00";
String str =time.substring(0,result.length() - 3);

Related

How to limited String in Android

In my application I want to show some text (date) into TextView.
I get this Text from server and I want to show this Text in TextView.
I get this Text from server :
16 Dec 2017
But I want to show such as this :
2017
How can I remove 16 Dec ?
try this
public static String getYyyy(String date) {
String time = date;
try {
SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy");
Date date1 = format.parse(date);
if (date1 != null) {
time = new SimpleDateFormat("yyyy").format(date1);
}
} catch (ParseException e) {
e.printStackTrace();
}
return time;
}
try this use split()
There are two signature for split() method in java string.
public String split(String regex)
and,
public String split(String regex, int limit)
use split a string in Java is to use .split(" ") which splits a string according to the pattern provided, returning a String array.
sample code
String date="16 Dec 2017";
String [] dateParts = date.split(" ");
String day = dateParts[0];
String month = dateParts[1];
String year = dateParts[2];
You can just separate the string with help of " " i.e. blank space, try to split the string with " " just like this:-
String date = "16 Dec 2017";
String[] date = date.split(" ");
//for only 2017 you can use date[2]
Be aware there are several ways more elegant and correct to do this, normally you use a Date object and just change how it looks like...
but to your wish, my answer:
I wouldnt split because is a waste to create an array for only getting one element of it...
you can use the substring method
String xdate = "16 Dec 2017";
System.out.println(xdate.substring(xdate.length() - 4, xdate.length()));
In java 8 you can do like this :
Date date = new Date(); //Create a Date object with date provided from TextBox
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int day = localDate.getDayOfMonth();
Since you only want the year int year = localDate.getYear(); will give you year.
if you want substring of date in which only Year i.e. last 4 number then try below code
String date="16 Dec 2017";
int a = date.length();
String d = date.substring(a-4,a);
You can try this as well rather then split if you have date & time or more date data
String requested_date = "16 Dec 2017";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM yyyy");
Date dateObj = simpleDateFormat.parse(requested_date,new ParsePosition(0));
dateObj.getYear();

java.lang.NumberFormatException: For input string: "02/10/2015"

i try to convert date like 02/10/2015 to string
i am trying but i get error
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "02/10/2015"
this is my code
private Crosshair xCrosshair;
long time = ds.getX(xy.getSeriesIndex(), xy.getItem()).longValue();
DecimalFormat dfT = new DecimalFormat("00");
GregorianCalendar gc = new GregorianCalendar();
long lDte = (long)time;
Date dtXX = new Date(lDte);
gc.setTime(dtXX);
String sDD = dfT.format(Double.valueOf(String.valueOf(gc.get(GregorianCalendar.DAY_OF_MONTH))));
String sMM = dfT.format(Double.valueOf(String.valueOf(gc.get(GregorianCalendar.MONTH)+1)));
String sYY = dfT.format(Double.valueOf(String.valueOf(gc.get(GregorianCalendar.YEAR))));
String dateString = sDD +"/"+ sMM +"/"+ sYY;
this.xCrosshair.setValue(Double.parseDouble(dateString));
This row
this.xCrosshair.setValue(Double.parseDouble(dateString));
try to convert a String that is a date to a Double (that is not a date)
You code cannot work:
String dateString = sDD +"/"+ sMM +"/"+ sYY;
this.xCrosshair.setValue(Double.parseDouble(dateString));
dateString will always have a / so it never will be correctly parsed.
For this use SimpleDateFormat:
DateFormat dt = new SimpleDateFormat("dd/MM/yyy");
long d = dt.parse(dateString).getTime();
As already pointed out, the error is happening because you are trying to parse a string that contains invalid characters, see:
http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#valueOf(java.lang.String)
If you want to parse the date as a double, then one possible solution would be:
String doubleString = sDD + sMM + sYY; // Simply leave the slashes out, but is this really what you're after?
this.xCrosshair.setValue(Double.parseDouble(doubleString));

unable to understand the cause of Number Format Exception

I have written a small program in which a user enters minutes and program shows the current Date and Time + minutes entered by the user.
final String DATE_FORMAT_NOW = "MM/dd/yyyy HH:mm:ss";
final DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.US);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, Integer.valueOf(sample.getMinutes()));
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
String dt = sdf.format(cal.getTime());
System.out.println(" Date and time with added Minutes : " + (dateFormat.parse(dt));
Sample
private String minutes;
//getter and setter
I am getting this exception
java.lang.NumberFormatException: For input string: ""
What I am doing wrong here?
Should I use
Integer.parseInt
or
Integer.valueOf(Integer.parseInt(sample.getMinutes())));?
With current date and time.
public static void main(String[] args)
{
try
{
final String DATE_FORMAT_NOW = "MM/dd/yyyy HH:mm:ss";
final DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.US);
Date sample = new Date();
int iMinutes = 30;//minutes added by the user
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, Integer.valueOf(sample.getMinutes()));
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
String dt = sdf.format(cal.getTime());
System.out.println("Current Date and time:"+sample);
System.out.println("Date and time with added Minutes : " + (dateFormat.parse(dt)));
}
catch (ParseException ex)
{
Logger.getLogger(NewMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
The output will be displays as:
Current Date and time:Tue Jun 12 15:57:55 IST 2012
Date and time with added Minutes : Tue Jun 12 16:54:55 IST 2012
Here the minutes "57" was added to the calendar and the time has moved forward by "30" mins.And that is the your result(Date and time with added Minutes).
With user in input minutes.
public static void main(String[] args)
{
try
{
final String DATE_FORMAT_NOW = "MM/dd/yyyy HH:mm:ss";
final DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.US);
int iMinutes = 30;//minutes added by the user
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, iMinutes);
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
String dt = sdf.format(cal.getTime());
System.out.println("Current Date and time:"+sample);
System.out.println("Date and time with added Minutes : " + (dateFormat.parse(dt)));
}
catch (ParseException ex)
{
Logger.getLogger(NewMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
This will work as per your desire first you take the minutes from the user and assign that minutes to the "iMinutes" variable of the code it will add that much minutes to the calander.
The output will be displayed as:
Current Date and time:Tue Jun 12 16:07:55 IST 2012
Date and time with added Minutes : Tue Jun 12 16:37:55 IST 2012
And if you want to set the minutes then use "set" instead of "add" in the "cal.add".
Hope this will solve your problem.
Regards.
Check if the returned string from sample.getMinutes() is a number or not. It must be a number without any white space to be parsed, otherwise you will get a NumberFormatException.
The problem you're having is that an empty string is not a valid integer. Your application should catch the exception, and set a sensible default instead.
"" is an empty string and it cannot be parsed into a valid integer given any circumstances
java.lang.NumberFormatException: For input string: ""
An empty String cannot be parsed to a number.
You need to check it first (using something like String#length() or StringUtils#isBlank()) and decide what to do with this case (for example treat it as zero).
java.lang.NumberFormatException: For input string: ""
Seems like you never set the minutes String
java.lang.NumberFormatException: For input string: ""
input String "" can not be converted into valid Integer.
before using Integer.parseInt, you ensure you are getting an integer by the following ways.
1.provide javascript validation for checking int
or/and
2.provide a server side validation for checking non-integer Strings
also see how to avoid NumberFormatException
Add some sort of checking:
final String DATE_FORMAT_NOW = "MM/dd/yyyy HH:mm:ss";
final DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.US);
Calendar cal = Calendar.getInstance();
final String minutes = sample.getMinutes()
cal.add(Calendar.MINUTE, Integer.valueOf((minutes != null && !minutes.isEmpty()) ? minutes : 0);
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
String dt = sdf.format(cal.getTime());
System.out.println(" Date and time with added Minutes : " + (dateFormat.parse(dt));
There is nothing unusal here. Read the java docs for parseInt() and valueOf which clearly states that a NumberFormatException is thrown if the String does not contain a parsable integer. And an empty string "" is not a parsable int.
It is up to you how you handle such cases for which a NumberFormatException is thrown.

How to get Date format like this in android?

How to get Date format like this?
Saturday,Dec 11,2011
Edited:
My code portion is like the following:
String outDate = "";
Date dT = new Date(year, mon, day);
SimpleDateFormat sdf = new SimpleDateFormat("EEE,MMM dd,yyyy");
outDate = sdf.format(dT);
and its output is `Sat,Dec 02,3911` when year = 2011,mon = 11,day = 2;
what is the reason of giving wrong month and year in output?
You can use SimpleDateFormat.
Try:
SimpleDateFormat formatter = new SimpleDateFormat("EEEE,MMM dd,yyyy");
String text = formatter.format(...);
That will use the default locale - adjust accordingly for a different one.
Try to use this function
Date today=new Date();
public String getCurrentTime()
{
SimpleDateFormat sdf = new SimpleDateFormat("EEEE,MM,dd,YYYY");
String ClsCurrentDay = sdf.format(today);
return ClsCurrentDay;
}

Date time object from webservice showing on Android textview with pattern?

Hi I have web service that return a date object like this as a return of the Json
"/Date(922312800000+0200)/"
However i need to show it on the textview in this pattern
"19.12.2011 16:15"
how can I convert that return to this pattern ?
Edit : Here is my code still giving java.lang.IllegalArgumentException
SimpleDateFormat date = new SimpleDateFormat("dd/MM/yy");
String dateText = date.format(tempEntry.getCreatedDate());
Edit : Here is the code that work for me
String dateText = tempEntry.getCreatedDate();
String dateString = dateText.replace("/Date(", "").replace(")/", "");
String[] dateParts = dateString.split("[+-]");
Date dateFormat = new Date(Long.parseLong(dateParts[0]))
It appears to me that your Date is given in milliseconds from 1970, so, something like that:
// remove the unneeded information
String date = date.replace("/Date(", "").replace(")/");
String[] dateParts = date.split("[+-]")
//get the date represented by the given millis
Calendar c = Calendar.getInstance();
c.setTime(Long.parseLong(dateParts[0]);
// proceed with formatting to the desired date format.
You need to use: DateFormat.
Simple example:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String today = formatter.format(date);
textView.setText("Today : " + today);

Categories