why parse exception Exception in thread "main" java.text.ParseException: Unparseable date: "Thu Jan 24 00:00:00 EET 2018 - parseexception

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");}
}
}

Related

Input from text file into linked list and displays in output file, also searched through index for date

Trying to get a linked list to read input from a file, put it into a linked list, search for same date, and write back into a file, UserLoginTest cannot be changed
public class User {``
String name;
int id;
String login;
double duration;
public User() {
name="";
id=0;
login="";
duration=0.0;
}
public User(String n,int i, String l, double d) {
n=name;
i=id;
l=login;
d=duration;
}
public void setName(String n) {
name=n;
}
public void setId(int i) {
id=i;
}
public void setLogin(String l) {
login=l;
}
public void setDuration(double d) {
duration =d;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public String getLogin() {
return login;
}
public double getDuration() {
return duration;
}
}
public class Node{
public User data;
Node next;
public Node(User u) {
data=u;
}
public Node(User u, Node n) {
data = u;
next = n;
}
public String toString() {
return data+"";
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
public class UserLoginTest {
public static void main(String[] args) throws FileNotFoundException {
String searchDate = "Oct 02";
String tempData;
String inputFileName = "Input.txt";
String outputFileName = "Output.txt";
UserLoginLinkedList loginList = generateLoginList(inputFileName);
tempData = "List of users who logged into the system";
//writeData(outputFileName, tempData);
writeData(outputFileName, loginList);
tempData = "List of users who logged into the system on "+searchDate;
//writeData(outputFileName, tempData);
//writeData(outputFileName, loginList.searchDate(searchDate, 0));
}
public static UserLoginLinkedList generateLoginList(String inputFileName) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
String loginList="";
File file = new File(inputFileName);
Scanner sc = new Scanner(file);
UserLoginLinkedList list = new UserLoginLinkedList();
while(sc.hasNextLine()) {
String temp = input.nextLine();
User u = new User(temp, 0, temp, 0);
list.add(u);
}
return list;
}
static void writeData(String inputFileName, UserLoginLinkedList loginList) {
try {
FileWriter f = new FileWriter(inputFileName, true);
PrintWriter p = new PrintWriter(f);
p.print(loginList.toString());
p.close();
}catch(Exception ex) {
}
}
}
public class UserLoginLinkedList{
Node head= null;
Node tail = null;
public void add(User u) {
Node newNode = new Node(u);
newNode.next = head;
head = newNode;
if(tail == null)tail = head;
}
public boolean searchDate(String searchDate,int id) {
Node current = head;
while (current != null) {//
if(current(searchDate) == searchDate)
return true;
current = current.next;
}
return false;
}
public String toString() {
String temp="";
Node current = head;
while (current != null) {
temp+=current.toString();
current = current.next;
}
return temp;
}
}
Input
aaa-123-Thu Oct 28 09:15:44 EDT 2021-22
abc-112-Thu Oct 28 09:20:45 EDT 2021-10
bbb-125-Fri Oct 29 09:15:44 EDT 2021-18
ccc-789-Sat Oct 02 09:15:44 EDT 2021-88
aaa-123-Sat Oct 02 19:15:44 EDT 2021-50
ddd-666-Wed Oct 13 09:15:44 EDT 2021-78
What is expected:
List of users who logged into the system
aaa 123 Thu Oct 28 09:15:44 EDT 2021 22
abc 112 Thu Oct 28 09:20:45 EDT 2021 10
bbb 125 Fri Oct 29 09:15:44 EDT 2021 18
ccc 789 Sat Oct 02 09:15:44 EDT 2021 88
aaa 123 Sat Oct 02 19:15:44 EDT 2021 50
ddd 666 Wed Oct 13 09:15:44 EDT 2021 78
List of users who logged into the system on Oct 02
ccc 789 Sat Oct 02 09:15:44 EDT 2021 88
aaa 123 Sat Oct 02 19:15:44 EDT 2021 50

How to change date and time format in flutter?

how are you ?
my backend just accept date and time in this format 2019-03-24 11:00:00
and i use in my app calendar widget to get the date and it print the date in this format 2019-04-24 12:00:00.000Z and i use this code to get the time
TimeOfDay _time = new TimeOfDay.now();
Future<Null> _selecTime(BuildContext context) async {
final TimeOfDay picked = await showTimePicker(
context: context,
initialTime: _time,
);
if (picked != null && picked != _time) {
print('${_time.toString()}');
setState(() {
_time = picked;
});
}
}
and i get this TimeOfDay(07:37)
so how can i get format for date like this 2019-04-24 and for time like this 11:00:00 and i will deal with it
thanks
You can use intl package
Here is an example:
import 'package:intl/intl.dart';
main() {
var now = new DateTime.now();
var dateFormat = new DateFormat('yyyy-MM-dd HH:mm:ss');
String formattedDate = dateFormat.format(now);
print(formattedDate); // 2019-04-28 09:02:29
}
You can do this task without any third-party package only by extensions.
void main() {
DateTime now = DateTime.now();
print(now.getTime24());
}
extension ExtractTime on DateTime {
String getTime24() => "$year-${month.addZero()}-${day.addZero()} ${hour.addZero()}:${minute.addZero()}:${second.addZero()}";
}
extension AddZero on int {
String addZero() => "${"$this".length==1?'0$this':this}";
}

How to extract date from tweets with lucene?

I have some tweets that I have already indexed "TweetIndexer" with lucene knowing that each tweet contains an ID, USER, TEXT, and DATE.
I want to only retrieve the date with another class "TweetSearcher" how to proceed?
Example of tweet:
"0","1467811372","Mon Apr 06 22:20:00 PDT 2009","NO_QUERY","joy_wolf","#Kwesidei not the whole crew ".
This my class TweetIndexer:
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class TweetIndexer {
protected static final String COMMA = "\",\"";
protected static final String POLARITY = "polarity";
protected static final String ID = "id";
protected static final String DATE = "date";
protected static final String QUERY = "query";
protected static final String USER = "user";
protected static final String TEXT = "text";
public static void main(String[] args) throws Exception {
try {
String indexDir = "D:\\tweet\\index";
String dataFile = "D:\\tweet\\collection\\tweets.csv";
TweetIndexer tweetIndexer = new TweetIndexer();
long start = System.currentTimeMillis();
int count = tweetIndexer.index(new File(indexDir), new File(dataFile));
System.out.print(String.format("Indexed %d documents in %d seconds", count, (System.currentTimeMillis() - start) / 1000));
}
catch (Exception e) {
System.out.println("Usage: java TweetIndexer <index directory> <csv data file>");
}
}
private int index(File indexDir, File dataFile) throws Exception {
IndexWriter indexWriter = new IndexWriter(
FSDirectory.open(indexDir),
new IndexWriterConfig(Version.LUCENE_44, new KeywordAnalyzer()));
int count = indexFile(indexWriter, dataFile);
indexWriter.close();
return count;
}
private int indexFile(IndexWriter indexWriter, File dataFile) throws IOException {
FieldType fieldType = new FieldType();
fieldType.setStored(true);
fieldType.setIndexed(true);
BufferedReader bufferedReader = new BufferedReader(new FileReader(dataFile));
String line = "";
int count = 0;
while ((line = bufferedReader.readLine()) != null) {
// Hack to ignore commas within elements in csv (so we can split on "," rather than just ,)
line = line.substring(1, line.length() - 1);
String[] tweetInfo = line.split(COMMA);
Document document = new Document();
document.add(new Field(POLARITY, tweetInfo[0], fieldType));
document.add(new Field(ID, tweetInfo[1], fieldType));
document.add(new Field(DATE, tweetInfo[2], fieldType));
document.add(new Field(QUERY, tweetInfo[3], fieldType));
document.add(new StringField(USER, tweetInfo[4], Field.Store.YES));
document.add(new StringField(TEXT, tweetInfo[5], Field.Store.YES));
indexWriter.addDocument(document);
count++;
}
return count;
}
}
And this is short java code for my class TweetSearcher:
public class TweetSearcher {
public static void main(String[] args) throws Exception {
try {
String indexDir = "D:\\tweet\\index";
int numHits = Integer.parseInt("3");
TweetSearcher tweetSearcher = new TweetSearcher();
tweetSearcher.dateSearch(new File(indexDir), numHits);
private void dateSearch(File indexDir, int numHits) throws Exception {
System.out.println("Find dates:");
Directory directory = FSDirectory.open(indexDir);
DirectoryReader directoryReader = DirectoryReader.open(directory);
IndexSearcher indexSearcher = new IndexSearcher(directoryReader);

Printing Calendar Sideways with the use of Calendar API

Hi guys So i have this problem.. i wanted to print a calendar, utilizing the Calendar API.
condition:
user inputs a Year, anInteger between 1000 - 9999.
then it will output the calendar of that year and 2 more succeeding years.
so if i input 2012 it will output the Calendar of 2012 , 2013 and 2014.
here is the catch it must be SIDEWAYS!
package lessons;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
public class lesson3 {
static String[] days = {"SUN","MON","TUE","WED","THU","FRI","SAT"};
static int counter = 0;
public static void main(String[] args) {
GregorianCalendar gcal = new GregorianCalendar();
Scanner scanner = new Scanner(System.in);
System.out.print("Year: ");
int input = scanner.nextInt(); //month input
//System.out.print("YEAR (): ");
//int input2 = scanner.nextInt();
scanner.close();
int year = input;
gcal.set(Calendar.YEAR,input);
for(int monthCount = 0;monthCount<12;monthCount++){
gcal.set(Calendar.MONTH,monthCount); // month counter 0 - 11 producing jan to dec.
monthCheck(monthCount); // converting months to readable names
int x = gcal.get(Calendar.DAY_OF_WEEK);
int max = gcal.getActualMaximum(Calendar.DAY_OF_MONTH);
for(int i = 0;i<days.length;i++){
System.out.printf("%8s",days[i]);
}
System.out.println("");
for(int i = 0; i < x-1;i++){
System.out.printf("%8s","");
counter++;
if(counter%7==0){
System.out.println("");
}
}
for(int i = 1;i<=max;i++){
System.out.printf("%8s",i);
counter++;
if(counter%7==0){
System.out.println("");
}
}
System.out.println("");
//System.out.println(x);
}
}
static void monthCheck(int monthCount){
ArrayList monthsList = new ArrayList<String>();
String[] months = new DateFormatSymbols().getMonths();
for (int i = 0; i < months.length-1; i++) {
String monthArr = months[i];
monthsList.add(months[i]);
}
System.out.println(months[monthCount]);
}
}
This is what i can do with the code Above, click here!
this is what i am aiming for now. CLICK HERE!

how to convert date from yyyy-MM-dd to dd-MMM-yyyy without using Date function

I have "2011-12-05" and I want to convert this to "Monday 05-Dec-2011".
My date conversion code depends on the device timezone. If my timezone is India, then I get date Monday 05-Dec-2011 and if my timezone is Kingston, Jamaica, I get Sunday 04-Dec-2011.
For this reason my application does not display the correct date for different timezones.
Is there any solution to convert date without Blackberry Date class or using current Date and Time Zone?
I want to only convert this date to String
I am converting this date using below function
public static String reformatMonthDate(String source)
{
SimpleDateFormat write = new SimpleDateFormat("dd MMM yyyy"); //YYYY-MMM-dd
Date date = new Date(HttpDateParser.parse(source));
return write.format(date);
}
You can specify a specific locale, instead of relying on the system's default.
Locale locale = Locale.get(Locale.LOCALE_fr);
// Parse with HttpDateParser
Date date = new Date(HttpDateParser.parse("2002-01-29"));
// Format with a custom format and locale
DateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy", locale);
StringBuffer buf = new StringBuffer(30);
String s = formatter.format(date, buf, null).toString(); // mar., 29 janv. 2002
DateTimePicker gives the current date according to the location or device configuration settings.
Try this code:
You should get your requirement.
public class LoadingScreen extends MainScreen implements FieldChangeListener
{
private String select_Date[]={"Select Date"};
private String month_ar[]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
private ObjectChoiceField choiceField;
private ButtonField show;
public LoadingScreen()
{
createGUI();
}
private void createGUI()
{
choiceField=new ObjectChoiceField("Select Date: ", select_Date, 0)
{
protected boolean navigationClick(int status, int time)
{
DateTimePicker datePicker = DateTimePicker.createInstance( Calendar.getInstance(), "dd/MM/yyyy",null);
datePicker.doModal();
Calendar cal1=datePicker.getDateTime();
String day="";
String mon="";
if(String.valueOf(cal1.get(Calendar.DAY_OF_MONTH)).length()==1)
{
day="0"+String.valueOf(cal1.get(Calendar.DAY_OF_MONTH));
}
else
{
day=String.valueOf(cal1.get(Calendar.DAY_OF_MONTH));
}
mon=String.valueOf(cal1.get(Calendar.MONTH));
String month=""+month_ar[cal1.get(Calendar.MONTH)];
select_Date[0]=day+"-"+month+"-"+cal1.get(Calendar.YEAR);
choiceField.setChoices(select_Date);
return true;
}
};
add(choiceField);
show=new ButtonField("Show",FIELD_HCENTER);
show.setChangeListener(this);
add(show);
}
public void fieldChanged(Field field, int context)
{
if(field==show)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert(select_Date[choiceField.getSelectedIndex()]);
}
});
}
}
public boolean onMenu(int instance)
{
return true;
}
protected boolean onSavePrompt()
{
return true;
}
}

Resources