Splitting a Java String - java

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

Related

Changing the date format from mm/dd/yyyy [duplicate]

This question already has answers here:
How can I change the date format in Java? [duplicate]
(10 answers)
Closed 7 years ago.
I need to change the date format from 2015-04-08 to 08-APR-2015.
It is coming from grails gsp front end.
Before calling oracle package I need to change the format in java.
How to do it.
I use SimpleDateFormat in changing date formats. Try this:
String OLD_FORMAT = "yyyy-MM-dd";
String NEW_FORMAT = "dd-MMM-yyyy";
String oldDateString = "2015-04-08";
String newDateString;
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = sdf.parse(oldDateString);
sdf.applyPattern(NEW_FORMAT);
newDateString = sdf.format(d);
You mentioned Java in your answer but you tagged JavaScript I've edited your question to show the Java tag. This is a JavaScript soution.
Assuming str is you input:
str.split('-').forEach(function(a,i,b){
result += i===0?(b[2]+'-'):i===1?(((new Date(str)).toUTCString()).split(' ')[2]+'-').toUpperCase():a[0];
});
Ok I already see and answer but still want to add one.I am not sure you want JS or Java solution. You can this using Javascript or Java. Below are both ways:
Javascript
var c = new Date('2015-04-08');
locale = "en-us"
function formatDate(d)
{
var month = d.toLocaleString(locale, { month: "long" });
var day = d.getDate();
day = day + "";
if (day.length == 1)
{
day = "0" + day;
}
return day + '-' + month +'-' + d.getFullYear();
}
And if you want same in Java you do below..
Java
String myDateString = "2015-04-08";
String reqDateString = new SimpleDateFormat("dd-MMM-yyyy").format(myDateString);
Better if done in Java looks more simpler and reliable..

Trying to parse the time

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.

Parse specific date string format

I have read a lot of questions and searched for a lot of libs all over the internet but I can't find one that can do this quickly.
I want to parse a specific date in a specific date format like this:
String date = "20130516T090000";
SimpleDateFormat x = new SimpleDateFormat("yyyyMMddTHHmmss");
String theMonth = x.parse(date, "M"); // 05
String theMonth = x.parse(date, "MMM"); // MAY
String theMinute = x.parse(date, "mm"); // 00
String theYear = x.parse(date, "yyyy"); // 2013
Just simple as that. A way to set a Parse Rule, a Specific Date Format and a way to retrieve each data i want (Month, Minute, Year....)
Is there a good library to do EXACTLY this? If yes could you put an example together? If no, is there a good way to do this without much code?
Thanks in advance!
Use the SimpleDateFormat class to parse a date from a String to a Date instance.
String date = "20130516T090000";
SimpleDateFormat x = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
Date d = x.parse(date);
There was a problem in your SimpleDateFormat format String, text in the format has to be quoted using single quoted (') to avoid interpretation.
Use the Calendar class to get the part of the date you want.
Calendar cal = Calendar.getInstance();
cal.setTime(d);
String theYear = String.valueOf(cal.get(Calendar.YEAR));
String theMonth = String.valueOf(cal.get(Calendar.MONTH));
String theMinute = String.valueOf(cal.get(Calendar.MINUTE));

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 + "-" + . . .

Date exception when trying to use date method

I have defined a object model where one of the array elements is a string
public static String[] columnNames6
= {"Total Shares",
"Total Calls",
"Call Strike",
"Call Premium",
"Call Expiry"
};
public static Object[][] data6
= {
{ new Double(0), new Double(0), new Double(0), new Double(0),"dd/mm/yyyy"},
};
I then use the following code to get the date so that I can use the data method but having
no joy - Can someone please tell me why it is throwing an exception after I do this
String ExpiryDate = (String)GV.data6[0][4];
System.out.println("DATE STRING IS: " + ExpiryDate);
Date EndOptionDate = new Date(ExpiryDate); // SOMETHING WRONG HERE even though it compiles okay
//Get Todays's Date
Date TodaysDate = new Date();
//Calculate Days Option Expiry
long DaysDifference = EndOptionDate.getTime() - TodaysDate.getTime();
Would really appreciate some help as really stuck not sure how I should code the
line in bold - new to java, so please excuses my lack of knowledge looked at tutorials
can't seem to move forward.
Thanks
Simon
ExpiryDate is a string try changing it to a date, its deprecated
Date(String s)
Deprecated. As of JDK version 1.1, replaced by DateFormat.parse(String s).
Here's an example:
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date today = df.parse("25/12/2010");
System.out.println("Today = " + df.format(today));
As said by JonH, you should use DateFormat.parse instead of new Date(String). Beside, your calculation of date difference is probably not good either:
//Calculate Days Option Expiry
long DaysDifference = EndOptionDate.getTime() - TodaysDate.getTime();
Will give you the difference in milliseconds between the two dates, not in days. You can use TimeUnit like this to obtain the day difference:
long dayDiff = TimeUnit.MILLISECONDS.toDays(EndOptionDate.getTime() - TodaysDate.getTime());

Categories

Resources