convert irregular dates - java

I got a list of irregular dates like this:
Thu, 29 Sep 2005 17:52:45 GMT
Wed, 17 Aug 2005 21:21:08 +0200
Wed, 17 Aug 2005 20:08:22 +0200
Mon, 15 Aug 2005 21:44:07 +0200
Sun, 24 Jul 2005 21:47:09 +0200
Sun, 24 Jul 2005 12:37:46 -0700 (PDT)
Sun, 24 Jul 2005 21:37:51 +0200
Mon, 11 Jul 2005 21:19:38 +0200
Mon, 11 Jul 2005 21:19:02 +0200
Mon, 11 Jul 2005 20:43:08 +0200 (CEST)
13 Nov 2006 14:06:20 +0000
How and can i convert them to DateTime or just Time with either JodaTime or the default java date class? (joda time prefered).

Each of those are following a certain DateFormat. Prepare a chain (chain of responsibility pattern) of predefined DateFormat handlers and pass the date String's you have into the chain. Let the appropriate handler parse the date and return the Date for you.
NOTE: This is assuming that the dates you have posted are available for you in string format. If you have a java.util.Date object then I believe what you are seeing is a display time format.

I Dont know buddy how to do it with jodatime, but what u can do is use
String pattern = "MM/dd/yyyy";
SimpleDateFormat format = new SimpleDateFormat(pattern);

Pangea i was to tired when i read your message, i wanted to post the solution and i read it back and now i realize i could have done it a lot easier with trying and on a null return or something try a different pattern.
Anyway this was the hard way solution:
String[] days = {
"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
};
String[] months = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
String[] years = {
"2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011"
};
// ORDER IS VERRY IMPORTANT!! ( MEST must be before EST for example)
String[] timesZones = {
"BST", "CET", "CEST", "CST", "CDT", "EDT", "GMT+00:00", "GMT", "IST", "MEST", "EST", "MET", "MDT", "PST", "PDT", "SAST", "UTC", "UT", "W. Europe Standard Time", "West-Europa (zomertijd)"
};
DateTime handleDate(String date) {
String origDate = date;
String timeZone = "";
String year = "";
String month = "";
String day = "";
int hours = 0;
int minutes = 0;
int seconds = 0;
// is it valid?
date = trim(date);
if (date.equals("")) {
return null;
}
// first delete the comma that comes mostly after the day
date = date.replaceAll(",", "");
// remove the day
for (int i = 0; i < days.length; i++) {
if (date.contains(days[i])) {
date = date.replace(days[i], "");
break;
}
}
// if(date.contains("23:27:17")) println(date);
for (int i = 0; i < timesZones.length; i++) {
// first check with '(' and ')'
String target = "("+timesZones[i]+")";
if (date.contains(target)) {
timeZone = timesZones[i];
date = date.replace(target, "");
break;
}
// if not found check without '(' and ')'
if (date.contains(timesZones[i])) {
timeZone = timesZones[i];
date = date.replace(timesZones[i], "");
break;
}
}
// get the month
for (int i = 0; i < months.length; i++) {
if (date.contains(months[i])) {
month = months[i].toLowerCase(); // !must be lowercase
// must be dutch on my pc
if(month.equals("oct")) month = "okt";
if(month.equals("may")) month = "mei";
if(month.equals("mar")) month = "mrt";
date = date.replace(months[i], "");
break;
}
}
// get the year
for (int i = 0; i < years.length; i++) {
if (date.contains(years[i])) {
year = years[i];
date = date.replace(years[i], "");
break;
}
}
// get the time
Pattern p = Pattern.compile("(\\d\\d):(\\d\\d):(\\d\\d)");
Matcher m = p.matcher(date);
if (m.find()) {
// also fix the time, 00 is not allowed
hours = int(m.group(1));
minutes = int(m.group(2));
seconds = int(m.group(3));
date = date.replaceAll("(\\d\\d:\\d\\d:\\d\\d)", "");
}
// get the time difference
date = date.replace("+-", "+0"); // bug fix where data is incorrect ( 16 Sep 2007 23:27:17 +-200)
p = Pattern.compile("[+|-]*(\\d\\d)\\d\\d");
m = p.matcher(date);
if (m.find()) {
int timeDifferenceH = int(m.group(1));
date = date.replaceAll("([+|-]*\\d\\d\\d\\d)", "");
}
date = " "+date; // bug fix
// get the day
for (int i = 31; i >= 1; i--) {
// first check for the ones that contains 2 digits (like 07)
String d = nf(i, 2);
if (date.contains(d)) {
day = nf(i, 2);
date = date.replace(d, "");
break;
}
// check for 1 digit
d = ""+i;
if (date.contains(d)) {
day = nf(i, 2);
date = date.replace(d, "");
break;
}
}
// there should be nothing left except white space
date = date.replace(" ", "");
if (date.equals("") == false) {
println("handleDate: problem with input\n"+date);
println(origDate+"\n");
println(year);
println(month);
println(day);
}
String cleanDate = day+"/"+month+"/"+year+" "+nf(hours, 2)+":"+nf(minutes, 2)+":"+nf(seconds, 2);
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MMM/yyyy HH:mm:ss");
try {
DateTime dt = formatter.parseDateTime(cleanDate);
return dt;
} catch (IllegalArgumentException iae) {
println("handleDate: Problem with formatting: "+cleanDate);
}
return null;
}

Related

what method can i use to change format 12 hours time to 24 hour time [duplicate]

In my app, I have a requirement to format 12 hours time to 24 hours time. What is the method I have to use?
For example, time like 10:30 AM. How can I convert to 24 hours time in java?
Try this:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String [] args) throws Exception {
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
Date date = parseFormat.parse("10:30 PM");
System.out.println(parseFormat.format(date) + " = " + displayFormat.format(date));
}
}
which produces:
10:30 PM = 22:30
See: http://download.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html
java.time
In Java 8 and later it could be done in one line using class java.time.LocalTime.
In the formatting pattern, lowercase hh means 12-hour clock while uppercase HH means 24-hour clock.
Code example:
String result = // Text representing the value of our date-time object.
LocalTime.parse( // Class representing a time-of-day value without a date and without a time zone.
"03:30 PM" , // Your `String` input text.
DateTimeFormatter.ofPattern( // Define a formatting pattern to match your input text.
"hh:mm a" ,
Locale.US // `Locale` determines the human language and cultural norms used in localization. Needed here to translate the `AM` & `PM` value.
) // Returns a `DateTimeFormatter` object.
) // Return a `LocalTime` object.
.format( DateTimeFormatter.ofPattern("HH:mm") ) // Generate text in a specific format. Returns a `String` object.
;
See this code run live at IdeOne.com.
15:30
See Oracle Tutorial.
Assuming that you use SimpleDateFormat implicitly or explicitly, you need to use H instead of h in the format string.
E.g
HH:mm:ss
instead of
hh:mm:ss
12 to 24 hour time conversion and can be reversed if change time formate in output and input SimpleDateFormat class parameter
Test Data Input:
String input = "07:05:45PM";
timeCoversion12to24(input);
output
19:05:45
public static String timeCoversion12to24(String twelveHoursTime) throws ParseException {
//Date/time pattern of input date (12 Hours format - hh used for 12 hours)
DateFormat df = new SimpleDateFormat("hh:mm:ssaa");
//Date/time pattern of desired output date (24 Hours format HH - Used for 24 hours)
DateFormat outputformat = new SimpleDateFormat("HH:mm:ss");
Date date = null;
String output = null;
//Returns Date object
date = df.parse(twelveHoursTime);
//old date format to new date format
output = outputformat.format(date);
System.out.println(output);
return output;
}
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
provided by Bart Kiers answer should be replaced with somethig like
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a",Locale.UK);
Try This
public static String convertTo24Hour(String Time) {
DateFormat f1 = new SimpleDateFormat("hh:mm a"); //11:00 pm
Date d = null;
try {
d = f1.parse(Time);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DateFormat f2 = new SimpleDateFormat("HH:mm");
String x = f2.format(d); // "23:00"
return x;
}
static String timeConversion(String s)
{
String s1[]=s.split(":");
char c[]=s1[2].toCharArray();
if(s1[2].contains("PM"))
{
int n=Integer.parseInt(s1[0]);
n=n+12;
return n+":"+s1[1]+":"+c[0]+c[1];
}
else``
return s1[0]+":"+s1[1]+":"+c[0]+c[1];
}
It can be done using Java8 LocalTime. Here is the code.
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class TimeConversion {
public String timeConversion(String s) {
LocalTime.parse(s, DateTimeFormatter.ofPattern("hh:mm a"));
}
}
And Here is the test case for the same:
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class TimeConversionTest {
#Test
void shouldReturnTimeIn24HrFormat() {
TimeConversion timeConversion = new TimeConversion();
Assertions.assertEquals("22:30", timeConversion.timeConversion("10:30 PM"));
}
}
Using LocalTime in Java 8, LocalTime has many useful methods like getHour() or the getMinute() method,
For example,
LocalTime intime = LocalTime.parse(inputString, DateTimeFormatter.ofPattern("h:m a"));
String outtime = intime.format(DateTimeFormatter.ISO_LOCAL_TIME);
In some cases, First line alone can do the required parsing
This is the extract of code that I have done.
String s="08:10:45";
String[] s1=s.split(":");
int milipmHrs=0;
char[] arr=s1[2].toCharArray();
boolean isFound=s1[2].contains("PM");
if(isFound){
int pmHrs=Integer.parseInt(s1[0]);
milipmHrs=pmHrs+12;
return(milipmHrs+":"+s1[1]+":"+arr[0]+arr[1]);
}
else{
return(s1[0]+":"+s1[1]+":"+arr[0]+arr[1]);
}
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;
public class Main {
public static void main(String [] args){
try {
DateFormat parseFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
String sDate = "22-01-2019 9:0:0 PM";
Date date = parseFormat.parse(sDate);
SimpleDateFormat displayFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sDate = displayFormat.format(date);
LOGGER.info("The required format : " + sDate);
} catch (Exception e) {}
}
}
Try this to calculate time difference between two times.
first it will convert 12 hours time into 24 hours then it will take diff between two times
String a = "09/06/18 01:55:33 AM";
String b = "07/06/18 05:45:33 PM";
String [] b2 = b.split(" ");
String [] a2 = a.split(" ");
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm:ss");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm:ss a");
String time1 = null ;
String time2 = null ;
if ( a.contains("PM") && b.contains("AM")) {
Date date = parseFormat.parse(a2[1]+" PM");
time1 = displayFormat.format(date);
time2 = b2[1];
}else if (b.contains("PM") && a.contains("AM")) {
Date date = parseFormat.parse(a2[1]+" PM");
time1 = a2[1];
time2 = displayFormat.format(date);
}else if (a.contains("PM") && b.contains("PM")){
Date datea = parseFormat.parse(a2[1]+" PM");
Date dateb = parseFormat.parse(b2[1]+" PM");
time1 = displayFormat.format(datea);
time2 = displayFormat.format(dateb);
}
System.out.println(time1);
System.out.println(time2);
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();
System.out.println(difference);
System.out.println("Duration: "+DurationFormatUtils.formatDuration(difference, "HH:mm"));
For More Details Click Here
I have written a simple utility function.
public static String convert24HourTimeTo12Hour(String timeStr) {
try {
DateFormat inFormat = new SimpleDateFormat( "HH:mm:ss");
DateFormat outFormat = new SimpleDateFormat( "hh:mm a");
Date date = inFormat.parse(timeStr);
return outFormat.format(date);
}catch (Exception e){}
return "";
}
Try this below code,
public static String timeConversion(String s) {
String militaryTime = "";
String hourString = s.substring(0,2);
String timeFormat = s.substring(8,10);
String timeBody = s.substring(2,8);
if (timeFormat.equals("AM")){
if (hourString.equals("12")){
militaryTime = "00" + timeBody;
}else{
militaryTime = hourString + timeBody;
}
}else if (timeFormat.equals("PM")){
if (hourString.equals("12")){
militaryTime = hourString + timeBody;
}else{
int value = Integer.parseInt(hourString) + 12;
militaryTime = String.valueOf(value) + timeBody;
}
}
return militaryTime;
}
Without using library methods
public static String timeConversion(String s) {
String[] timeElements = s.split(":");
if (s.contains("PM")) {
timeElements[0] = getPMHours(timeElements[0]);
} else {
timeElements[0] = getAMHours(timeElements[0]);
}
timeElements[2] = timeElements[2].substring(0,2);
return timeElements[0]+":"+timeElements[1]+":"+timeElements[2];
}
private static String getAMHours(String hour) {
if(Integer.parseInt(hour) == 12) return "00";
return hour;
}
private static String getPMHours(String hour) {
int i = Integer.parseInt(hour);
if(i != 12) return 12+i+"";
return i+"";
}
I was looking for same thing but in number, means from integer xx hour, xx minutes and AM/PM to 24 hour format xx hour and xx minutes, so here what i have done:
private static final int AM = 0;
private static final int PM = 1;
/**
* Based on concept: day start from 00:00AM and ends at 11:59PM,
* afternoon 12 is 12PM, 12:xxAM is basically 00:xxAM
* #param hour12Format
* #param amPm
* #return
*/
private int get24FormatHour(int hour12Format,int amPm){
if(hour12Format==12 && amPm==AM){
hour12Format=0;
}
if(amPm == PM && hour12Format!=12){
hour12Format+=12;
}
return hour12Format;
}`
private int minutesTillMidnight(int hour12Format,int minutes, int amPm){
int hour24Format=get24FormatHour(hour12Format,amPm);
System.out.println("24 Format :"+hour24Format+":"+minutes);
return (hour24Format*60)+minutes;
}
We can solve this by using String Buffer
String s;
static String timeConversion(String s) {
StringBuffer st=new StringBuffer(s);
for(int i=0;i<=st.length();i++){
if(st.charAt(0)=='0' && st.charAt(1)=='1' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '3');
}else if(st.charAt(0)=='0' && st.charAt(1)=='2' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '4');
}else if(st.charAt(0)=='0' && st.charAt(1)=='3' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '5');
}else if(st.charAt(0)=='0' && st.charAt(1)=='4' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '6');
}else if(st.charAt(0)=='0' && st.charAt(1)=='5' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '7');
}else if(st.charAt(0)=='0' && st.charAt(1)=='6' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '8');
}else if(st.charAt(0)=='0' && st.charAt(1)=='7' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '9');
}else if(st.charAt(0)=='0' && st.charAt(1)=='8' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '0');
}else if(st.charAt(0)=='0' && st.charAt(1)=='9' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '1');
}else if(st.charAt(0)=='1' && st.charAt(1)=='0' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '2');
}else if(st.charAt(0)=='1' && st.charAt(1)=='1' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '3');
}else if(st.charAt(0)=='1' && st.charAt(1)=='2' &&st.charAt(8)=='A' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '0');
st.setCharAt(1, '0');
}else if(st.charAt(0)=='1' && st.charAt(1)=='2' &&st.charAt(8)=='P' ){
st.setCharAt(0, '1');
st.setCharAt(1, '2');
}
if(st.charAt(8)=='P'){
st.setCharAt(8,' ');
}else if(st.charAt(8)== 'A'){
st.setCharAt(8,' ');
}
if(st.charAt(9)=='M'){
st.setCharAt(9,' ');
}
}
String result=st.toString();
return result;
}

Counting occurrences of an item not giving exactly in android

I am trying to count the occurrence of the each string. If the month matches with current, then I'm displaying count of the that string.
Suppose this month is 07 and modifiedtime months are like 07, 06, 09, 06, 07 in that what are the month 07 are there for that month what is count of the each item
Example: Month = 07 , count of opportunity should be 1,
output:
What I'm getting :
Count_opportunity:02
Count_proposal:02
Count_negotiation:01
Count_won:32
Count_lost:17
Desired output:
Count_opportunity:01
Count_proposal:0
Count_negotiation:0
Count_won:0
Count_lost:0
The following code gives me a wrong count. Can some-one detect the error?
private void workingOnResponseMonthwiseOpportunity(SyncModule syncModule){
String success = syncModule.getSuccess();
if (success.equals("true")) {
SyncResults results = syncModule.getResult();
Sync sync = results.getSync();
ArrayList<SyncUpdated> syncUpdateds = sync.getUpdated();
for (SyncUpdated syncUpdated : syncUpdateds) {
ArrayList<SyncBlocks> syncBlocks = syncUpdated.getBlocks();
String scheduleDates = "";
String scheduleDate = "";
String supportrequired="";
String winprob="";
String salesstage="";
String modality="";
String modifydatetime="";
String modifiedtime="";
String date1 = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
for (SyncBlocks syncBlocks1 : syncBlocks) {
String label = syncBlocks1.getLabel();
if (label.equals("Basic Information")) {
ArrayList<SynFields> synFields = syncBlocks1.getFields();
for (SynFields synFields1 : synFields) {
name = synFields1.getName();
values = synFields1.getValue();
//sales stage
if (name.equals("sales_stage")) {
salesstage = String.valueOf(values);
salesstage_list.add(salesstage);
//support required
}
}
}
else if (label.equals("Opportunity Details")) {
ArrayList<SynFields> synFields = syncBlocks1.getFields();
for (SynFields synFields1 : synFields) {
String name = synFields1.getName();
values = synFields1.getValue();
if (("modifiedtime".equals(name))) {
modifydatetime = String.valueOf(values);
Log.d("modifydatetime",modifydatetime);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
modifiedmonth= LocalDateTime.from(LocalDateTime.parse(modifydatetime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
Log.d("modifiedmonth", String.valueOf(modifiedmonth));
break;
}
}
}
PreferenceManagerMyOpportunity.getInstance(requireContext()).setMultipleDataOpportunity(scheduleDate, salesstage, supportrequired, winprob, modality,modifiedtime);
}
MyOpportunityModel opportunityModel = new MyOpportunityModel(scheduleDate, salesstage, supportrequired, winprob, modality, modifydatetime);
java.time.LocalDate today = java.time.LocalDate.now();
int month=today.getMonthValue();
Log.d("month",String.valueOf(month));
boolean isModifiedThisMonth =modifiedmonth==month;
Log.d("isModifiedThisMonth",String.valueOf(isModifiedThisMonth));
if (isModifiedThisMonth) {
//Sales stage starts
Count_opportunity = Collections.frequency(salesstage_list, "Opportunity");
System.out.println("Count_opportunity: "+ Count_opportunity);
Count_proposal = Collections.frequency(salesstage_list, "Proposal or Price Quote");
//System.out.println("Count of In Complete is: "+ Count_Incomplete);
Count_negotiation = Collections.frequency(salesstage_list, "Negotiation or Review");
Count_won = Collections.frequency(salesstage_list, "Closed Won");
Count_lost = Collections.frequency(salesstage_list, "Closed Lost");
// System.out.println("Count of Completed is: "+ Complted_Count);
}
}
}
}
}

java parse date time with milliseconds into date getting parse error

I have a string in which I am finding the datetime with milliseconds as follows:
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
String monthup = String.valueOf(month);
String dayup = String.valueOf(day);
String hourup = String.valueOf(hour);
String minuteup = String.valueOf(minute);
String secondup = String.valueOf(second);
String millisup = String.valueOf(millis);
if(monthup.length()==1){monthup="0"+monthup;}
if(dayup.length()==1){dayup="0"+dayup;}
if(hourup.length()==1){hourup="0"+hourup;}
if(minuteup.length()==1){minuteup="0"+minuteup;}
if(secondup.length()==1){secondup="0"+secondup;}
if(millisup.length()==1){millisup="0"+millisup;}
if(millisup.length()==2){secondup="00"+millisup;}
String timewithmilsec = year+ monthup + dayup+ hourup+ minuteup+ secondup+ millisup;
System.out.println(timewithmilsec);
I am getting a value: 20151020115216690 which is obviousely correct.
I want to parse it to java Date format.
What I did is as follows:
try{
DateFormat formatter = new SimpleDateFormat("yyyyMMdHHmmssaaa");
Date date = formatter.parse(timewithmilsec);
System.out.println(date);
}
catch(Exception e){
System.out.println(e);
}
I am getting an error as follows:
java.text.ParseException: Unparseable date: "20151020115247995"
You have only one d in your format, but are padding the day to two characters, also, according to the JavaDocs...
a Am/pm marker Text PM
which isn't a millisecond place holder, I think you mean SSS
For example...
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
String monthup = String.valueOf(month);
String dayup = String.valueOf(day);
String hourup = String.valueOf(hour);
String minuteup = String.valueOf(minute);
String secondup = String.valueOf(second);
String millisup = String.valueOf(millis);
if (monthup.length() == 1) {
monthup = "0" + monthup;
}
if (dayup.length() == 1) {
dayup = "0" + dayup;
}
if (hourup.length() == 1) {
hourup = "0" + hourup;
}
if (minuteup.length() == 1) {
minuteup = "0" + minuteup;
}
if (secondup.length() == 1) {
secondup = "0" + secondup;
}
if (millisup.length() == 1) {
millisup = "0" + millisup;
}
if (millisup.length() == 2) {
secondup = "00" + millisup;
}
String timewithmilsec = year + monthup + dayup + hourup + minuteup + secondup + millisup;
System.out.println(timewithmilsec);
try {
DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
Date date = formatter.parse(timewithmilsec);
System.out.println(date);
} catch (Exception e) {
System.out.println(e);
}
Which for me prints
20151020173034124
Tue Oct 20 17:30:34 EST 2015
And while I'm at it, let me introduce you to String.format, which can reduce all you int to String conversion and padding code down to...
String timewithmilsec = String.format("%04d%02d%02d%02d%02d%02d%03d", year, month, day, hour, minute, second, millis);
I am getting Tue Oct 20 12:04:08 IST 2015 but interestingly I did not see any millisecond here
Date#toString won't include the milliseconds by default, you will need to supply a DateFormat which can.
If I replace the last System.out.println with System.out.println(new SimpleDateFormat("dd MMM yyyy HH:mm:ss.SSS").format(date)); it prints something like
20 Oct 2015 17:37:14.856
(for the value 20151020173714856)
According to documentation letter S responds to milliseconds so your format should look like this new SimpleDateFormat("yyyyMMddHHmmssSSS"); (you have one d in your format).
The answer is the missing "d" in the date format, where #MadProgrammer depicts.
In addition, the generation of the string representation of the date should be reconsidered. You should use SimpleDateFormat.format() to generate date string as in the sample code below:
Calendar now = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String formattedDate = formatter.format(now.getTime());
System.out.println("Formatted date: " + formattedDate);
And the output will be in a format that you requested.
Formatted date: 20151020094934279

Java get int numbers from DateFormat and have user Input

In my code I want to have the individual numbers from date format so I can use them as int values:
public static final String DATE_FORMAT = "dd.MM.yyyy";
public int age()
{
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date date = new Date();
// How to convert to int?
int currentnDay = ?;
int currentMonth = ?;
int currentYear = ?;
}
also I would like some user input to define day,month and year in one go, if that's even possible:
private Date dateOfPublication;
public void input()
{
Scanner scn = new Scanner( System.in );
System.out.print( "Please enter dateOfPublication: " );
// How to setup input for this?
}
I hope you can help me out, previously I did it all seperatly but the code was quite big and I think it would be prettier if I could do it like that..
update: okay I'm doing the input like this now:
System.out.print( "Please enter dateOfPublication, use format of x.x.xxxx: " );
userInputDate = scn.next();
String[] ary = userInputDate.split("\\.");
publicationDay = Integer.parseInt(ary[0]);
publicationMonth = Integer.parseInt(ary[1]);
publicationYear = Integer.parseInt(ary[2]);
thanks for your help!
Take a look at Java 8's new Time API (or JodaTime or Calendar if you're really stuck)
LocalDate ld = LocalDate.parse("16.10.2015", DateTimeFormatter.ofPattern(DATE_FORMAT));
System.out.println(ld);
System.out.println(ld.getDayOfMonth());
System.out.println(ld.getMonth().getValue());
System.out.println(ld.getYear());
Which outputs
2015-10-16
16
10
2015
Now, you could simply ask the user to input a date in a given format and try and parse the result, if the parsing fails, you could reprompt them
For example...
Scanner input = new Scanner(System.in);
LocalDate ld = null;
do {
System.out.print("Please enter date in " + DATE_FORMAT + " format: ");
String value = input.nextLine();
try {
ld = LocalDate.parse(value, DateTimeFormatter.ofPattern(DATE_FORMAT));
} catch (Exception e) {
System.err.println(value + " is not a valid date for the format of " + DATE_FORMAT);
}
} while (ld == null);
System.out.println(ld);
System.out.println(ld.getDayOfMonth());
System.out.println(ld.getMonth().getValue()); // Is probably 0 indexed
System.out.println(ld.getYear());
You can use:
dateFormat.format(today).split("\\.");
For your code:
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date date = new Date();
String[] dateArr = dateFormat.format(today).split("\\.");
int currentnDay = Integer.parseInt(dateArr[0]);
int currentMonth = Integer.parseInt(dateArr[1]);
int currentYear = Integer.parseInt(dateArr[2]);
IdeOne Example
First, you have to parse the input string
The Calendar data type is more flexible for date-time handling. This is an example that shows some Date/Calendar operations.
Date date;
Calendar c;
// Get the current date
c = Calendar.getInstance();
System.out.println("Current Calendar:" + c.getTime().toString());
int currentnDay = c.get(Calendar.DATE);
int currentMonth = c.get(Calendar.MONTH);
int currentYear = c.get(Calendar.YEAR);
System.out.println(String.format("Current Values: %d/%d/%d",
currentnDay, currentMonth, currentYear));
String DATE_FORMAT = "dd.MM.yyyy";
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
date = dateFormat.parse("11.10.1981");
System.out.println("Modified Date:" + date.toString());
// reset Calendar
c = Calendar.getInstance();
// set date to the calendar
c.setTimeInMillis(date.getTime());
currentnDay = c.get(Calendar.DATE);
currentMonth = c.get(Calendar.MONTH);
currentYear = c.get(Calendar.YEAR);
System.out.println(String.format("Modified Values: %d/%d/%d",
currentnDay, currentMonth, currentYear));
This is the output of the example.
Current Calendar:Thu Oct 15 20:22:59 EDT 2015
Current Values: 15/9/2015
Modified Date:Sun Oct 11 00:00:00 EDT 1981
Modified Values: 11/9/1981

java.lang.StringIndexOutOfBoundsException: Exception

I am trying to read a log file and trying to print all the logs between a certain dates but i end up getting this exception when am trying to retrieve date from the log.
this is my code and it is actually printing some log messages
public class Teat {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
{
// TODO Auto-generated method stub
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy");
BufferedReader br = new BufferedReader(new FileReader(
"C:\\log.log"));
String sCurrentLine;
try {
String startDate = "12 Dec 2013";
String endDate = "12 Dec 2013";
Date dateStart = formatter.parse(startDate);
Date dateEnd = formatter.parse(endDate);
Date logDate = null;
int sDay = dateStart.getDate();
int sMonth = dateStart.getMonth();
int sYear = dateStart.getYear();
int eDay = dateEnd.getDate();
int eMonth = dateEnd.getMonth();
int eYear = dateEnd.getYear();
String date;
int i=0;
ArrayList<String> Sub_string = new ArrayList<String>();
do {
sCurrentLine = br.readLine();
Sub_string.add(sCurrentLine.substring(0, 11));
logDate = formatter.parse(Sub_string.get(i));
int lDay = logDate.getDate();
int lMonth = logDate.getMonth();
int lYear = logDate.getYear();
if (lYear >= sYear && lYear <= eYear)
{
if (lMonth >= sMonth && lMonth <= eMonth)
{
if (lDay >= sDay && lDay <= eDay) {
System.out.println(sCurrentLine);
}
}
}
else{System.out.println("pls ented valid dates");}
i++;
}while(sCurrentLine!=null);
}
catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
error is
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index
out of range: 11
at java.lang.String.substring(Unknown Source)
at Teat.main(Teat.java:41)
Change whlie((sCurrentLine = br.readLine())!=null) instead of do while otherwise you will end with NullPointerException.
and check if(sCurrentLinet.isEmpty()&&sCurrentLinet.length()>=11) before processing.
yes what is the value of that line ? – Jigar Joshi 3 mins ago edit
the value is 12 Dec 2013 – user3117965 19 secs ago
12 Dec 2013 is 11 character long String so the last character is at the position 10 (first character is at 0 index), accessing 11th element will give put you out of bound and so the Exception
Sub_string.add(sCurrentLine.substring(0, 11));
is giving problem. Add a check before calling the substring(start, end) function
if (sCurrentLine != null && end>= start && end <= sCurrentLine.length())
Did you check whether all the lines in the log are atleast 11 characters long? You will get StringOutOfBoundsException if any of the lines are less than 11 chars in your case.
Also please change your code according to the suggestion from #Prabhakaran.

Categories