How correctly convert this String using substring() Java method? - java

I have the following problem using the substring() Java function.
I have to do the following operation:
I have a String representing a date having the following form: 2014-12-27 (YEARS-MONTH-DAY).
And I want convert it into a String like this: 20141227 (without the space betwen date component).
So I have implemented the following method that use the substring() method to achieve this task:
private String convertDate(String dataPar) {
String convertedDate = dataPar.substring(0,3) + dataPar.substring(5,6) + dataPar.substring(8,9);
return convertedDate;
}
But it don't work well and return to me wrong conversion. Why? What am I missing?

Use replace method which will replace all ocurrences of '-' for '':
private String convertDate(String dataPar) {
return dataPar.replace('-', '');
}

A simple way would be to replace all the occurrences of -. If the separator could be different then maybe using SimpleDateFormat would be better.
private String convertDate(String dataPar) {
return datapar.replaceAll("-", "");
}

Try replaceAll (This ll replace - with "" means it ll remove -) :
private String convertDate(String dataPar) {
if(dataPar.length() > 0){
return dataPar.replaceAll("-","");
}
return "NOVAL";
}

If the input is only a date, you can use the SimpleDateFormat and use a format like yyMMdd http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

I want you to just change the end indeces of the substring() methods as given below
String convertedDate = dataPar.substring(0,4) + dataPar.substring(5,7) + dataPar.substring(8,10);
I tested, It works Fine as you requested :)

private String convertDate(String dataPar) {
final String year = dataPar.substring(0, 4);
final String month = dataPar.substring(5, 7);
final String day = dataPar.substring(8, 10);
return year + month + day;
}

Related

Remove elements from Date Format String using a Regular Expression

I want to remove elements a supplied Date Format String - for example convert the format "dd/MM/yyyy" to "MM/yyyy" by removing any non-M/y element.
What I'm trying to do is create a localised month/year format based on the existing day/month/year format provided for the Locale.
I've done this using regular expressions, but the solution seems longer than I'd expect.
An example is below:
public static void main(final String[] args) {
System.out.println(filterDateFormat("dd/MM/yyyy HH:mm:ss", 'M', 'y'));
System.out.println(filterDateFormat("MM/yyyy/dd", 'M', 'y'));
System.out.println(filterDateFormat("yyyy-MMM-dd", 'M', 'y'));
}
/**
* Removes {#code charsToRetain} from {#code format}, including any redundant
* separators.
*/
private static String filterDateFormat(final String format, final char...charsToRetain) {
// Match e.g. "ddd-"
final Pattern pattern = Pattern.compile("[" + new String(charsToRetain) + "]+\\p{Punct}?");
final Matcher matcher = pattern.matcher(format);
final StringBuilder builder = new StringBuilder();
while (matcher.find()) {
// Append each match
builder.append(matcher.group());
}
// If the last match is "mmm-", remove the trailing punctuation symbol
return builder.toString().replaceFirst("\\p{Punct}$", "");
}
Let's try a solution for the following date format strings:
String[] formatStrings = { "dd/MM/yyyy HH:mm:ss",
"MM/yyyy/dd",
"yyyy-MMM-dd",
"MM/yy - yy/dd",
"yyabbadabbadooMM" };
The following will analyze strings for a match, then print the first group of the match.
Pattern p = Pattern.compile(REGEX);
for(String formatStr : formatStrings) {
Matcher m = p.matcher(formatStr);
if(m.matches()) {
System.out.println(m.group(1));
}
else {
System.out.println("Didn't match!");
}
}
Now, there are two separate regular expressions I've tried. First:
final String REGEX = "(?:[^My]*)([My]+[^\\w]*[My]+)(?:[^My]*)";
With program output:
MM/yyyy
MM/yyyy
yyyy-MMM
Didn't match!
Didn't match!
Second:
final String REGEX = "(?:[^My]*)((?:[My]+[^\\w]*)+[My]+)(?:[^My]*)";
With program output:
MM/yyyy
MM/yyyy
yyyy-MMM
MM/yy - yy
Didn't match!
Now, let's see what the first regex actually matches to:
(?:[^My]*)([My]+[^\\w]*[My]+)(?:[^My]*) First regex =
(?:[^My]*) Any amount of non-Ms and non-ys (non-capturing)
([My]+ followed by one or more Ms and ys
[^\\w]* optionally separated by non-word characters
(implying they are also not Ms or ys)
[My]+) followed by one or more Ms and ys
(?:[^My]*) finished by any number of non-Ms and non-ys
(non-capturing)
What this means is that at least 2 M/ys are required to match the regex, although you should be careful that something like MM-dd or yy-DD will match as well, because they have two M-or-y regions 1 character long. You can avoid getting into trouble here by just keeping a sanity check on your date format string, such as:
if(formatStr.contains('y') && formatStr.contains('M') && m.matches())
{
String yMString = m.group(1);
... // other logic
}
As for the second regex, here's what it means:
(?:[^My]*)((?:[My]+[^\\w]*)+[My]+)(?:[^My]*) Second regex =
(?:[^My]*) Any amount of non-Ms and non-ys
(non-capturing)
( ) followed by
(?:[My]+ )+[My]+ at least two text segments consisting of
one or more Ms or ys, where each segment is
[^\\w]* optionally separated by non-word characters
(?:[^My]*) finished by any number of non-Ms and non-ys
(non-capturing)
This regex will match a slightly broader series of strings, but it still requires that any separations between Ms and ys be non-words ([^a-zA-Z_0-9]). Additionally, keep in mind that this regex will still match "yy", "MM", or similar strings like "yyy", "yyyy"..., so it would be useful to have a sanity check as described for the previous regular expression.
Additionally, here's a quick example of how one might use the above to manipulate a single date format string:
LocalDateTime date = LocalDateTime.now();
String dateFormatString = "dd/MM/yyyy H:m:s";
System.out.println("Old Format: \"" + dateFormatString + "\" = " +
date.format(DateTimeFormatter.ofPattern(dateFormatString)));
Pattern p = Pattern.compile("(?:[^My]*)([My]+[^\\w]*[My]+)(?:[^My]*)");
Matcher m = p.matcher(dateFormatString);
if(dateFormatString.contains("y") && dateFormatString.contains("M") && m.matches())
{
dateFormatString = m.group(1);
System.out.println("New Format: \"" + dateFormatString + "\" = " +
date.format(DateTimeFormatter.ofPattern(dateFormatString)));
}
else
{
throw new IllegalArgumentException("Couldn't shorten date format string!");
}
Output:
Old Format: "dd/MM/yyyy H:m:s" = 14/08/2019 16:55:45
New Format: "MM/yyyy" = 08/2019
I'll try to answer with the understanding of my question : how do I remove from a list/table/array of String, elements that does not exactly follow the patern 'dd/MM'.
so I'm looking for a function that looks like
public List<String> removeUnWantedDateFormat(List<String> input)
We can expect, from my knowledge on Dateformat, only 4 possibilities that you would want, hoping i dont miss any, which are "MM/yyyy", "MMM/yyyy", "MM/yy", "MM/yyyy". So that we know what we are looking for we can do an easy function.
public List<String> removeUnWantedDateFormat(List<String> input) {
String s1 = "MM/yyyy";
string s2 = "MMM/yyyy";
String s3 = "MM/yy";
string s4 = "MMM/yy";
for (String format:input) {
if (!s1.equals(format) && s2.equals(format) && s3.equals(format) && s4.equals(format))
input.remove(format);
}
return input;
}
Better not to use regex if you can, it costs a lot of resources. And great improvement would be to use an enum of the date format you accept, like this you have better control over it, and even replace them.
Hope this will help, cheers
edit: after i saw the comment, i think it would be better to use contains instead of equals, should work like a charm and instead of remove,
input = string expected.
so it would looks more like:
public List<String> removeUnWantedDateFormat(List<String> input) {
List<String> comparaisons = new ArrayList<>();
comparaison.add("MMM/yyyy");
comparaison.add("MMM/yy");
comparaison.add("MM/yyyy");
comparaison.add("MM/yy");
for (String format:input) {
for(String comparaison: comparaisons)
if (format.contains(comparaison)) {
format = comparaison;
break;
}
}
return input;
}

how to convert csv date format from yyyy/mm/ddd to yyyymmdd

I am trying to import a csv with a date in the following format:
2018/01/25
the date format in mysql is in Int and I want to remove the slashes in the current date format.
I need to get the date looking like this:
20180125
I need to work only on the first column and not the rest of the csv.
here is the code for reading the csv.
while(reader.readLine()!= null)
{
String read = reader.readLine();//bufferedreader string variable
String [] rawRow = read.split(",");
String lastEntry = rawRow[rawRow.length-1];// this contains MemberNo/branchNo
String [] properLastEntry = lastEntry.split("/");//this contains MemberNo,BranchNo
//memory that contains rawRow nd properLastEntry in a single array
String [] oneRow = new String[rawRow.length+1];
System.arraycopy(rawRow, 0, oneRow, 0,rawRow.length-1);
System.arraycopy(properLastEntry, 0, oneRow, oneRow.length - properLastEntry.length,properLastEntry.length);
System.out.println(Arrays.toString(oneRow));
rs2.add(oneRow);
}
Why wouldn't it come from the database in a java.sql.Date object?
Well, if you're reading it as a string, just do this:
String convert(String dateIn) {
String year = dateIn.subString(0,4);
String month = dateIn.subString(5,7);
String day = dateIn.subString(8);
return year + month + day;
}
Of course it's still a very bad idea to read the date as a String from the database, because the format is not guaranteed to be the same on every server. Could be one on your test server and another on the production.
/**
*
* #author CHIRAG
*
*/
public class DateConverter {
public static void main(String... args) {
String date = "2018/01/25";
System.out.println(date + " converted to -> " + convertDate(date));
}
public static String convertDate(String date) {
return date.replaceAll("/|-", ""); // it will remove all occurrences of '/' or '-'
}
}
The output of this code snip is:
2018/01/25 converted to -> 20180125
Only you have to pass date string to the method convertDate(String date)
Happy Coding :)

Remove parts of String? [duplicate]

I want to remove a part of string from one character, that is:
Source string:
manchester united (with nice players)
Target string:
manchester united
There are multiple ways to do it. If you have the string which you want to replace you can use the replace or replaceAll methods of the String class. If you are looking to replace a substring you can get the substring using the substring API.
For example
String str = "manchester united (with nice players)";
System.out.println(str.replace("(with nice players)", ""));
int index = str.indexOf("(");
System.out.println(str.substring(0, index));
To replace content within "()" you can use:
int startIndex = str.indexOf("(");
int endIndex = str.indexOf(")");
String replacement = "I AM JUST A REPLACEMENT";
String toBeReplaced = str.substring(startIndex + 1, endIndex);
System.out.println(str.replace(toBeReplaced, replacement));
String Replace
String s = "manchester united (with nice players)";
s = s.replace(" (with nice players)", "");
Edit:
By Index
s = s.substring(0, s.indexOf("(") - 1);
Use String.Replace():
http://www.daniweb.com/software-development/java/threads/73139
Example:
String original = "manchester united (with nice players)";
String newString = original.replace(" (with nice players)","");
originalString.replaceFirst("[(].*?[)]", "");
https://ideone.com/jsZhSC
replaceFirst() can be replaced by replaceAll()
Using StringBuilder, you can replace the following way.
StringBuilder str = new StringBuilder("manchester united (with nice players)");
int startIdx = str.indexOf("(");
int endIdx = str.indexOf(")");
str.replace(++startIdx, endIdx, "");
You should use the substring() method of String object.
Here is an example code:
Assumption: I am assuming here that you want to retrieve the string till the first parenthesis
String strTest = "manchester united(with nice players)";
/*Get the substring from the original string, with starting index 0, and ending index as position of th first parenthesis - 1 */
String strSub = strTest.subString(0,strTest.getIndex("(")-1);
I would at first split the original string into an array of String with a token " (" and the String at position 0 of the output array is what you would like to have.
String[] output = originalString.split(" (");
String result = output[0];
Using StringUtils from commons lang
A null source string will return null. An empty ("") source string will return the empty string. A null remove string will return the source string. An empty ("") remove string will return the source string.
String str = StringUtils.remove("Test remove", "remove");
System.out.println(str);
//result will be "Test"
If you just need to remove everything after the "(", try this. Does nothing if no parentheses.
StringUtils.substringBefore(str, "(");
If there may be content after the end parentheses, try this.
String toRemove = StringUtils.substringBetween(str, "(", ")");
String result = StringUtils.remove(str, "(" + toRemove + ")");
To remove end spaces, use str.trim()
Apache StringUtils functions are null-, empty-, and no match- safe
Kotlin Solution
If you are removing a specific string from the end, use removeSuffix (Documentation)
var text = "one(two"
text = text.removeSuffix("(two") // "one"
If the suffix does not exist in the string, it just returns the original
var text = "one(three"
text = text.removeSuffix("(two") // "one(three"
If you want to remove after a character, use
// Each results in "one"
text = text.replaceAfter("(", "").dropLast(1) // You should check char is present before `dropLast`
// or
text = text.removeRange(text.indexOf("("), text.length)
// or
text = text.replaceRange(text.indexOf("("), text.length, "")
You can also check out removePrefix, removeRange, removeSurrounding, and replaceAfterLast which are similar
The Full List is here: (Documentation)
// Java program to remove a substring from a string
public class RemoveSubString {
public static void main(String[] args) {
String master = "1,2,3,4,5";
String to_remove="3,";
String new_string = master.replace(to_remove, "");
// the above line replaces the t_remove string with blank string in master
System.out.println(master);
System.out.println(new_string);
}
}
You could use replace to fix your string. The following will return everything before a "(" and also strip all leading and trailing whitespace. If the string starts with a "(" it will just leave it as is.
str = "manchester united (with nice players)"
matched = str.match(/.*(?=\()/)
str.replace(matched[0].strip) if matched

Java: replacing characters in a String

I have a String that represents a time value and is stored in the following format:
1:31:25
I would like to replace the colons and change the format to:
1h 31m 25s
What function in Java will let me replace the first two colons with 'h ' and 'm ', and the end of the string with 's'.
You could do something like this:
String[] s = myString.split(":");
String.format("%sh %sm %ss", s);
Or even compact!
String.format("%sh %sm %ss", myString.split(":"));
String time = "1:31:25";
String formattedTime = time.replaceFirst(":","h ").replaceFirst(":","m ").concat("s");
String input = "1:31:25";
String[] tokens = input.split(":");
String output = tokens[0] + "h " + tokens[1] + "m " + tokens[2] + "s";
Repeated use of the String.replaceFirst() method would help you here.
Simply replace your first ':' with the 'h', then apply again for 'm' etc.
There are additional options, which may be more appropriate/robust etc. depending on your circumstances.
Regular expressions may be useful here, to help you parse/split up such a string.
Or given that you're parsing/outputting times, it may also be worth looking at SimpleDateFormat and its ability to parse/output date/time combinations.
In fact, if you're storing that date as a string, you may want to revist that decision. Storing it as a date object (of whatever variant) is more typesafe, will protect you against invalid values, and allow you to perform arithmetic etc on these.
String[] timeStr = "1:31:25".split(":");
StringBuffer timeStrBuf = new StringBuffer();
timeStrBuf.append(timeStr[0]);
timeStrBuf.append("h ");
timeStrBuf.append(timeStr[1]);
timeStrBuf.append("m ");
timeStrBuf.append(timeStr[2]);
timeStrBuf.append("s");
You can use a regular expression and substitution:
String input = "1:31:25";
String expr = "(\\d+):(\\d+):(\\d+)";
String substitute = "$1h $2m $3s";
String output = input.replaceAll(expr, substitute);
An alternative is to parse and output the String through Date:
DateFormat parseFmt = new SimpleDateFormat("HH:mm:ss");
DateFormat displayFmt = new SimpleDateFormat("H'h' mm\'m' ss's'");
Date d = parseFmt.parse(input);
output = displayFmt.format(d);
Use split()
String s = "1:31:25";
String[] temp = s.split(":");
System.out.println(s[0]+"h"+" "+s[1]+"m"+" "+s[2]+"s");

How to convert / cast long to String?

I just created sample BB app, which can allow to choose the date.
DateField curDateFld = new DateField("Choose Date: ",
System.currentTimeMillis(), DateField.DATE | DateField.FIELD_LEFT);
After choosing the date, I need to convert that long value to String, so that I can easily store the date value somewhere in database.
I am new to Java and Blackberry development.
long date = curDateFld.getDate();
How should I convert this long value to String? Also I want to convert back to long from String. I think for that I can use long l = Long.parseLong("myStr");?
See the reference documentation for the String class: String s = String.valueOf(date);
If your Long might be null and you don't want to get a 4-letter "null" string, you might use Objects.toString, like: String s = Objects.toString(date, null);
EDIT:
You reverse it using Long l = Long.valueOf(s); but in this direction you need to catch NumberFormatException
String strLong = Long.toString(longNumber);
Simple and works fine :-)
Long.toString()
The following should work:
long myLong = 1234567890123L;
String myString = Long.toString(myLong);
very simple,
just concatenate the long to a string.
long date = curDateFld.getDate();
String str = ""+date;
1.
long date = curDateFld.getDate();
//convert long to string
String str = String.valueOf(date);
//convert string to long
date = Long.valueOf(str);
2.
//convert long to string just concat long with empty string
String str = ""+date;
//convert string to long
date = Long.valueOf(str);
String logStringVal= date+"";
Can convert the long into string object, cool shortcut for converting into string...but use of String.valueOf(date); is advisable
Just do this:
String strLong = Long.toString(longNumber);
String longString = new String(""+long);
or
String longString = new Long(datelong).toString();

Categories

Resources