convert array objects into time - java

If i have an Array which contains the Strings 07:46:30 pm , 10:45:28 pm , 07:23:39 pm , .......
and I want to convert it into Time. How can i do this?

Here's how to convert an array of Strings in the given format to an array of dates:
public static Date[] toDateArray(final String[] dateStrings)
throws ParseException{
final Date[] arr = new Date[dateStrings.length];
int pos = 0;
final DateFormat df = new SimpleDateFormat("K:mm:ss a");
for(final String input : dateStrings){
arr[pos++] = df.parse(input);
}
return arr;
}

Use the SimpleDateFormat class. Here is an example:
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
for(String str : array){
Date date = formatter.parse(str);
}

Use the SimpleDateFormat class to parse the date.

You need to write your own parser. See this example:
http://www.kodejava.org/examples/101.html

If you want a array or list of time...
String[] arrString = new String[] { "07:46:30 pm", "10:45:28 pm", "07:23:39 pm" }
Time[] arrTime = new Time[strArray.lengh];
or
List<Time> listTime = new ArrayList<Time>();
Array string to array or list time:
//For array
for (int i = 0; i < arrString.length; i++) {
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
Date date = formatter.parse(arrString[i]);
//Populate the ARRAY
arrTime[i] = new Time(date.getTime());
}
//For list
for (String str : arrString) {
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
Date date = formatter.parse(str);
//Populate the LIST
listTime.add(new Time(date.getTime()));
}

Related

Change date format from m/dd/yy to yyyy/MM/dd in Java

I have this Date in a String with a 2 digit year.
I need to convert in another format. I tried with SampleDateFormat but it didn't work.
The SampleDateFormat is giving wrong format i.2 date with UTC and timestamp
I want in yyyy/MM/dd only.
Is there any other way to do this?
String receiveDate = "7/20/21";
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
try {
rdate = sdf.parse(receiveDate);
} catch (ParseException e) {
e.printStackTrace();
}
String recievedt = rdate.toString();
String dateParts[] = recievedt.split("/");
// Getting day, month, and year from receive date
String month = dateParts[0];
String day = dateParts[1];
String year = dateParts[2];
int iday = Integer.parseInt(day);
int imonth = Integer.parseInt(month);
int iyear = Integer.parseInt(year);
LocalDate date4 = LocalDate.of(iyear, imonth, iday).plusDays(2*dueoffset);
If you can use the java.time API I would suggest something along the lines of the following:
String input = "7/20/21";
LocalDate receivedDate = LocalDate.parse(input, DateTimeFormatter.ofPattern("M/dd/yy"));
String formatted = receivedDate.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
// or if you actually need the date components
int year = receivedDate.getYear();
...
How is String receiveDate="7/20/21"; a valid date?
String dateStr = "07/10/21";
SimpleDateFormat receivedFormat = new SimpleDateFormat("yy/MM/dd");
SimpleDateFormat finalFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = receivedFormat.parse(dateStr);
System.out.println(finalFormat.format(date)); // 2007/10/21
This, however, requires that you have date with leading zeros for year, month and date. If that is not the case, please sanitize your date string.
public static String sanitizeDateStr(String dateStr) {
String dateStrArr[] = dateStr.split("/");
String yearStr = String.format("%02d", Integer.parseInt(dateStrArr[0]));
String monthStr = String.format("%02d", Integer.parseInt(dateStrArr[1]));
String dayStr = String.format("%02d", Integer.parseInt(dateStrArr[2]));
return String.format("%s/%s/%s", yearStr, monthStr, dayStr);
}
public static void main (String[] args) throws Exception {
String dateStr = sanitizeDateStr("7/10/21");
SimpleDateFormat receivedFormat = new SimpleDateFormat("yy/MM/dd");
SimpleDateFormat finalFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = receivedFormat.parse(dateStr);
System.out.println(finalFormat.format(date));
}

Why do I get a parse exception

this programe should subtract 2 days tare3 and tare4 . tare3 valued from current day (from system ) tare4 value from text file (element [3]) , when i parsed string (element[3]) to date (tare4) its give`me parseexception
date saved in file looked like (Thu Jan 24 00:00:00 EET 2018)
package javaapplication3;
import java.io.*; ` `
import java.util.*;
import java.text.*;
public static void main(String[] args) throws ParseException, FileNotFoundException {
private static String tare5 = new String();
static String tare2 = new String ();
DateFormat dateFormat = new SimpleDateFormat(" dd MMM yyyy ",Locale.ENGLISH );
Calendar cal = Calendar.getInstance();
Date tare4 = new Date ();
tare5 = dateFormat.format(cal.getTime());
Date tare3 = dateFormat.parse(tare5);
Scanner scanner;
File Myfile = new File("C:\\Users\\mido\\Documents\\NetBeansProjects\\JavaApplication3\\src\\javaapplication3\\products.txt");
scanner = new Scanner (Myfile);
while (scanner.hasNext()){
String line = scanner.nextLine();
StringTokenizer x = new StringTokenizer(line,"~");
String [] element= new String [7];
int counter = 0 ;
while (x.hasMoreElements())
{
element[counter]=(String)x.nextElement();
counter ++;
}
tare4 = dateFormat.parse(element[3]);
if (tare4.getTime()>= tare3.getTime() )
{
System.out.println(element[1]+"is expired");
}
else {
long def = tare3.getTime()- tare4.getTime();
System.out.println(element[1]+"has"+def+"to expire");}
}
}
The stacktrace is as :
Exception in thread "main" java.text.ParseException: Unparseable date: "20/10/2015 " at java.text.DateFormat.parse(DateFormat.java:357) at javaapplication3.JavaApplication3.main(JavaApplication3.java:51)
Your input 20/10/2015 doesn't meet the cases to fall under the dateFormat. You might want to change
SimpleDateFormat(" dd MMM yyyy ",Locale.ENGLISH )
to
SimpleDateFormat("dd/MM/yyyy",Locale.ENGLISH )

Compare formatted dates to integers in Java

I would like to compare a Date I get from my local machine to an integer I get from a scanner. The date is formated as: MMDDYYYY such as 11232015 which is todays date. My integer is then 11192015. I want to convert my date to an integer and then compare the true date vs. the one I got from my scanner:
Calendar c;
DateFormat df = new SimpleDateFormat("MMddyyyy");
c.getInstance();
Date currentDate = c.getTime();
int dateFromScanner = 11192015;
Date formattedDate = df.format(currentDate);
if (dateFromScanner !> formattedDate {
// Do some stuff
} else {
System.out.println("This date has not yet passed.");
}
But I cannot compare dates to integers.
You can do something like that:
DateFormat df = new SimpleDateFormat("MMddyyyy");
Date currentDate = new Date();
int dateFromScanner = 11192015;
try {
Date formattedDateFromScanner = df
.parse(String.valueOf(dateFromScanner));
if (formattedDateFromScanner.before(currentDate)) {
// Do some stuff
} else {
System.out.println("This date has not yet passed.");
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try a solution like this, it can give you some idea what do you do.
public static void main(String[] args) {
Calendar c = null;
Scanner sc = new Scanner(System.in);
System.out.println("Enter date value like yyyyMMdd.");
int dat = sc.nextInt();
DateFormat df = new SimpleDateFormat("yyyyMMdd");
Date currentDate = c.getInstance().getTime();
String formattedDate = df.format(currentDate);
System.out.println(formattedDate);
if (dat < Integer.parseInt(formattedDate)) {
System.out.println("This date had being passed.");
} else {
System.out.println("This date has not yet passed.");
}
}

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

multidimensional array convert to date java

I have:
int lineTable = Table.getRowCount();
int columnTable= Table.getColumnCount();
Object[][] arrayTable = new Object[lineTable ][columnTable];
for (int j = 0; j < lineTable ; j++) {
for (int i = 0; i < columnTable; i++) {
arrayTable [j][i] = Table.getValueAt(j, i);
}
}
With this, I have a multidimensional array type Object with all data of the table... Can I convert this array to date(HH:mm)?
PS: The data is already in this format(HH:mm), but I don't know how take this directly in date format...
I did it! Just made these changes:
int lineTable = Table.getRowCount();
int columnTable= Table.getColumnCount();
Date[][] arrayTable = new Date[lineTable ][columnTable];
for (int j = 0; j < lineTable ; j++) {
for (int i = 0; i < columnTable; i++) {
arrayTable [j][i] = (Date)Table.getValueAt(j, i);
}
}
Thanks for all!
You can use the SimpleDateFormat class to parse the String to Date object like this:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String str = yourArray[x][x] + ":" + yourArray[x][x]
Date date = sdf.parse(str);
Try something like this:
public static void main(String[] args) throws ParseException {
DateFormat df = new SimpleDateFormat("MM-dd-yyyy"); //your format here
Date date = df.parse("11-3-1985");
System.out.println("" + date);
}
This will parse a date in the given format. You can also create another DateFormat for formatting the date when you print if if you want a different format example:
public static void main(String[] args) throws ParseException {
DateFormat df = new SimpleDateFormat("MM-dd-yyyy"); //your format here
DateFormat df1 = new SimpleDateFormat("MM/dd/yyyy");
Date date = df.parse("11-3-1985");
System.out.println("" + df1.format(date));
}
This is just an example you can use whatever format you want...if you only want to give hours and seconds do that.

Categories