I have a list of object Strings with some Hebrew and English mixed. The Sentence always starts with Hebrew. My GOAL output is:
אדר: Mon, 40 minutes and 11 חלקים after 12:00 PM
ניסן: Wed, 24 minutes and 12 חלקים after 1:00 AM
אייר: Thu, 8 minutes and 13 חלקים after 2:00 PM
סיון: שבת, 52 minutes and 14 חלקים after 2:00 AM
Current output:
I've tried interject the left to right bytes such as "\u202E" + "שבת" + "\u202D" but I can't find a combination of code that makes this uniformly work.
At a minimum if I print the cell starting with an English character it starts in the right place, but the Hebrew after the colon starts the same issue:
Here is some Sample Java code to generate the above
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.*;
import org.junit.Test;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class TestHebrew {
int rowNumber = 1;
XSSFSheet sheet;
XSSFRow row;
#Test
public void TestHebrewEnglishInterlace() throws IOException {
List<MyObject> objects = new ArrayList<>();
objects.add(new MyObject("אדר", "Mon, 40 minutes and 11 חלקים after 12:00 PM"));
objects.add(new MyObject("ניסן", "Wed, 24 minutes and 12 חלקים after 1:00 AM"));
objects.add(new MyObject("אייר", "Thu, 8 minutes and 13 חלקים after 2:00 PM"));
objects.add(new MyObject("סיון", "Sat, 52 minutes and 14 חלקים after 2:00 AM"));
objects.get(3).description = objects.get(3).description.replace("Sat", "שבת");
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
sheet = workbook.createSheet("TestSheet");
row = sheet.createRow(rowNumber);
XSSFCellStyle style = workbook.createCellStyle();
style.setWrapText(true);
style.setAlignment(HorizontalAlignment.LEFT);
for (MyObject o : objects) {
addCellAndNextRow(style, o.month + ":" + "" + o.description);
}
addCellAndNextRow(style, "");
addCellAndNextRow(style, "Same values but appending English first");
addCellAndNextRow(style, "");
for (MyObject o : objects) {
addCellAndNextRow(style, "a " + o.month + ": " + "" + o.description);
}
IntStream.range(0, 1).forEach(i -> sheet.autoSizeColumn(i));
try (FileOutputStream out = new FileOutputStream(FileSystemView.getFileSystemView().getHomeDirectory().toPath().resolve("output.xlsx").toFile())) {
workbook.write(out);
}
Desktop.getDesktop().open(FileSystemView.getFileSystemView().getHomeDirectory().toPath().resolve("output.xlsx").toFile());
}
}
private void addCellAndNextRow(XSSFCellStyle style, String value) {
XSSFCell cell = row.createCell(0);
cell.setCellStyle(style);
cell.setCellValue(value);
row = sheet.createRow(++rowNumber);
}
static class MyObject {
String month;
String description;
public MyObject(String month, String description) {
this.month = month;
this.description = description;
}
}
}
Related
How can I print all months first and the last date which falls within the given specified Month-Year range?
So far I have the code which prints for 1 complete year example, if in the input year 2019 is provided then the first and the last date of all 12 months is printed. But what I want is it should print values within the specified Month-Year range.
Example,
String input_StartMonthYear = "1-2019";
String input_EndMonthYear = "6-2020";
Expected Output:
firstDay-> 2019-1-1
lastDay-> 2019-1-31
firstDay-> 2019-2-1
lastDay-> 2019-2-28
---
---
firstDay-> 2020-6-1
lastDay-> 2020-6-30
Code:
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
public class GetDate_Firt_Last {
static String input_Year = "2019";
static String completeinput;
static int totalmonths[] = {1,2,3,4,5,6,7,8,9,10,11,12};
public static void main (String args[]) throws Exception
{
int m;
for (m = 1;m <= totalmonths.length;m++)
{
completeinput = m + "-" + input_Year;
SimpleDateFormat sdf = new SimpleDateFormat("MM-yyyy");
Date date = sdf.parse(completeinput);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
getFirstDayOfTheMonth(cal);
getLastDayOfTheMonth(cal);
System.out.println();
}
}
public static String getFirstDayOfTheMonth(Calendar cal) throws Exception {
String firstDay;
try {
int firstDate = cal.getActualMinimum(Calendar.DATE);
int month = cal.get(Calendar.MONTH) +1;
int year = cal.get(Calendar.YEAR);
firstDay = year + "-" + month + "-" + firstDate;
System.out.println("firstDay-> " +firstDay);
} catch (Exception e) {
throw new Exception("Exception in getFirstDayOfTheMonth." + e.getMessage());
}
return firstDay;
}
public static String getLastDayOfTheMonth(Calendar cal) throws Exception {
String lastDay;
try {
int lastDate = cal.getActualMaximum(Calendar.DATE);
int month = cal.get(Calendar.MONTH)+1;
int year = cal.get(Calendar.YEAR);
lastDay = year + "-" + month + "-" + lastDate;
System.out.println("lastDay-> "+ lastDay);
} catch (Exception e) {
throw new Exception("Exception in getLastDateOfTheMonth." + e.getMessage());
}
return lastDay;
}
}
Actual Output:
firstDay-> 2019-1-1
lastDay-> 2019-1-31
firstDay-> 2019-2-1
lastDay-> 2019-2-28
---
---
firstDay-> 2019-12-1
lastDay-> 2019-12-31
If you use java 8 or higher something like this could be a first approach
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
public class GetDate_Firt_Last {
public static void main(String[] args) {
String input_StartMonthYear = "1-2019";
String input_EndMonthYear = "6-2020";
DateTimeFormatter df = DateTimeFormatter.ofPattern("d-M-yyyy");
LocalDate start = LocalDate.parse("1-" +input_StartMonthYear, df);
LocalDate end = LocalDate.parse("1-" + input_EndMonthYear, df);
for(LocalDate d = start; d.isBefore(end.plusMonths(1)); d = d.plusMonths(1)){
System.out.println("firstDay -> " + d.with(TemporalAdjusters.firstDayOfMonth()));
System.out.println("lastDay -> " + d.with(TemporalAdjusters.lastDayOfMonth()));
System.out.println();
}
}
}
Eritrean’s answer is fine. In case you fancy a stream solution, here’s one:
DateTimeFormatter monthYearFormatter = DateTimeFormatter.ofPattern("M-u");
Period step = Period.ofMonths(1);
String inputStartMonthYear = "1-2019";
String inputEndMonthYear = "6-2020";
LocalDate startDateInclusive
= YearMonth.parse(inputStartMonthYear, monthYearFormatter).atDay(1);
LocalDate endDateExclusive = YearMonth
.parse(inputEndMonthYear, monthYearFormatter)
.plusMonths(1)
.atDay(1);
startDateInclusive.datesUntil(endDateExclusive, step)
.forEach(d1 -> {
System.out.println("firstDay-> " + d1);
LocalDate endOfMonth = d1.with(TemporalAdjusters.lastDayOfMonth());
System.out.println("lastDay-> " + endOfMonth);
});
The output is longish, so I am giving you just the first and the last lines:
firstDay-> 2019-01-01
lastDay-> 2019-01-31
firstDay-> 2019-02-01
lastDay-> 2019-02-28
firstDay-> 2019-03-01
lastDay-> 2019-03-31
firstDay-> 2019-04-01
lastDay-> 2019-04-30
(... cut ...)
firstDay-> 2020-05-01
lastDay-> 2020-05-31
firstDay-> 2020-06-01
lastDay-> 2020-06-30
I'm developing an API in which one of the object should satisfy the below:
I've a column in Postgress DB as :
input = 201800
Input(column -datatype is character[6]) 201801
.
.
.
201812
Requirement :
Check if the input is current year
check if the last 2 digits are zeros , then ignore
if it is 201802 : dd=01(always), 02(Month) and 2018(year)
after checking the conditions, if it satisfies display like this :
For Ex: input = 201803 then o/p should in MM/DD/YYYY h:m format
Always month is 01 for month in between (01-12),O/P = 01/03/2018 12:00
I tried this, but didn't gibe O/P as per ,y requirement:
public class sample {
public static void main(String[] args) {
try {
String input= "201700" + "00";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
Date d = sdf1.parse(input);
System.out.print(d);
String formateDate = new SimpleDateFormat("MM/dd/yyyy hh:mm").format(d);
System.out.print(formateDate);
} catch(Exception e) {}
}
}
Appreciate your help!
I created a method mapDate() that is actually verifying your condition and return the wanted output. You just have to pass the value as parameter to the method. See the example below:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(String[] args) {
String result1 = mapDate("201802"+"00");
System.out.print("result: " + result1 + "\n");
String result2 = mapDate("201702"+"02");
System.out.print("result: " + result2 + "\n");
String result3 = mapDate("201802"+"02");
System.out.print("result: " + result3);
}
public static String mapDate(String value){
String myDate;
myDate = "";
SimpleDateFormat format1 = new SimpleDateFormat("yyyy");
String thisYear = format1.format(new Date());
if(!value.substring(value.length() - 2).equals("00") && value.substring(0, 4).equals(thisYear))
myDate = "01/" + value.substring(4, 6) + "/" + value.substring(0, 4) + " 12:00";
return myDate;
}
}
The ouput of this example is:
result:
result:
result: 01/02/2018 12:00
i have a text file that has date/time, name, amount tipped, total tips
I am able to get it reduced to just names (In one arraylist) and amount tipped(in a second arraylist)
Now IM trying to get it to where it adds up the amount tipped per person.
So if X tipped 10,20,30,40 it will output X tipped 100.
From Text file
Dec. 6, 2013, 8:31 p.m. Tip from y
25 7687
Dec. 6, 2013, 8:30 p.m. Tip from x
30 7662
Dec. 6, 2013, 8:30 p.m. Tip from z
25 7632
Dec. 6, 2013, 8:31 p.m. Tip from z
25 7687
Dec. 6, 2013, 8:30 p.m. Tip from z
30 7662
Dec. 6, 2013, 8:30 p.m. Tip from x
25 7632
Here is where I am at so far
import java.io.*;
import java.util.*;
public class TipTester {
public static void main(String[] args) {
int lineNumber = 1;
List<String> name = new ArrayList<String>();
List<String> tip = new ArrayList<String>();
String fileName = "C:\\Users\\David\\Desktop\\tips.txt";
System.out.println("Reading text from file");
try {
FileReader inputFile = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(inputFile);
String line;
while ((line = bufferedReader.readLine()) != null) {
if (lineNumber % 2 != 0) {
System.out.println(line.substring(line.indexOf("from ") + 5) + "\\");
name.add(line.substring(line.indexOf("from ") + 5) + "\\");
} else {
System.out.println(line.substring(0, line.indexOf("\t")) + "\\");
tip.add(line.substring(0, line.indexOf("\t")) + "\\");
}
lineNumber ++;
}
bufferedReader.close();
name.add("-");
tip.add("-");
} catch (Exception e) {
System.out.println("Error while reading file line by line: " + e.getMessage());
}
}
}
Try this
tip.add("-"); // take this line out...
double totalTip = 0; // an accumulator.
for (String tipStr : tip) {
if (tipStr != null) {
try {
totalTip += Double.valueOf(tipStr.trim()); // Add the tips.
} catch (NumberFormatException e) {
}
}
}
System.out.println("totalTip = " + totalTip);
Date Emp_Code Emp_Name Cardno Shift_Start IN OUT Shift_End Status Emp_Late Left_Early Hours_Worked O T OS
26. Jan. 2011 001 KL Acharya 000001 9:00 9:15 18:34 18:00 P 0.15 0.00 9.19 0:00 0:34
26. Jan. 2011 002 Seemakiran Upadhya 000002 9:00 18:00 A 0:00
26. Jan. 2011 013 Sumana Ravishankar 000013 9:00 18:00 A 0:00
26. Jan. 2011 017 Gopalkrishna Prabhau KV 000017 9:00 18:00 A 0:00
26. Jan. 2011 021 Sarath Modali 000021 20:00 21:02 6:40 6:00 P 1.02 0.00 9.38 0:00 0:40
26. Jan. 2011 023 Siddharth Singh 000023 9:00 18:00 A 0:00
26. Jan. 2011 034 Meghana K 000034 9:00 18:00 A 0:00
26. Jan. 2011 036 Rajendra KS 000036 9:00 18:00 A 0:00
26. Jan. 2011 037 Rajesh K 000037 9:00 18:00 A 0:00
26. Jan. 2011 039 Mahesh PR 000039 9:00 18:00 A 0:00
26. Jan. 2011 041 Krishnamoorthy A 000041 9:00 18:00 A 0:00
26. Jan. 2011 047 Smruti Ranjan Panda 000047 9:00 18:00 A 0:00
26. Jan. 2011 049 Raghuraman K 000049 9:00 1:12 18:00 MS 0.00 0:00
26. Jan. 2011 055 Raghavendra HS 000055 9:00 18:00 A 0:00
26. Jan. 2011 063 Anoop Chandran U 000063 9:00 18:00 A 0:00
26. Jan. 2011 069 Ramesh Kumar Hegde 000069 9:00 18:00 A 0:00
26. Jan. 2011 070 Mohan T 000070 9:00 18:00 A 0:00
26. Jan. 2011 078 Shurabh Chaubey 000078 20:00 9:38 10:49 6:00 A 0.00 0.00 1.11 0:00
26. Jan. 2011 079 Sourabha Mahopatra 000079 9:00 18:00 A 0:00
this is my excel sheet which containing some blank cells in between. so i could nor read the sheet properly. Can any body give me a way to do it.so while reading row wise the column count decreses when it fins a blank cell in between.
To interact with Office Documents the only real solution is to use an API such as Apache POI
APACHE POI library all the way
Use poi-3.8!
This can deal blank cells !
package com.vaadin.addon.tableimport;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
public class ExcelImport implements Serializable {
private static final long serialVersionUID = -8404407996727936498L;
protected HSSFWorkbook workbook;
/** The totals row. */
protected Row titleRow, headerRow, totalsRow;
protected Row hierarchicalTotalsRow;
protected FileInputStream is = null;
/**輔助存儲*/
private List<List<Object>> data;
private int headLineNum;
public ExcelImport(File file, String dealString) {
//獲得表頭行數
headLineNum = reflex(dealString);
//System.out.println("表頭行數 : " + headLineNum);
try {
is = new FileInputStream(file);
workbook = new HSSFWorkbook(is);
} catch (IOException e) {
e.printStackTrace();
}
HSSFSheet childSheet = workbook.getSheetAt(0);
//System.out.println("有Physical行数" + childSheet.getPhysicalNumberOfRows());
//System.out.println("有行数" + childSheet.getLastRowNum() + " , " +childSheet.getFirstRowNum());
Object o;
data = new ArrayList<List<Object>>();
for (int aa = headLineNum; aa < childSheet.getPhysicalNumberOfRows(); aa++) {
data.add(new ArrayList<Object>());
for (int bb = 0; bb < childSheet.getRow(aa).getLastCellNum(); bb++) {
data.get(aa-headLineNum).add(new String());
}
}
for (int j = 0; j < childSheet.getPhysicalNumberOfRows(); j++) {
HSSFRow row = childSheet.getRow(j);
//System.out.println("有Physical列数" + row.getPhysicalNumberOfCells());
//System.out.println("有列数" + row.getLastCellNum());
if (null != row) {
for (int k = 0; k < row.getLastCellNum(); k++) {
HSSFCell cell = row.getCell(k);
if (null != cell) {
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC: // 数字
//System.out.print(cell.getNumericCellValue() + " ");
//o = String.valueOf(cell.getNumericCellValue());
o = cell.getNumericCellValue();
break;
case HSSFCell.CELL_TYPE_STRING: // 字符串
//System.out.print(cell.getStringCellValue() + " ");
//o = String.valueOf(cell.getStringCellValue());
o =cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
//System.out.println(cell.getBooleanCellValue() + " ");
//o = String.valueOf(cell.getBooleanCellValue());
o =cell.getBooleanCellValue();
break;
case HSSFCell.CELL_TYPE_FORMULA: // 公式
//System.out.print(cell.getCellFormula() + " ");
//o = String.valueOf(cell.getCellFormula());
o =cell.getCellFormula();
break;
case HSSFCell.CELL_TYPE_BLANK: // 空值 -->Null Value
//System.out.println(" ");
o = " ";
break;
case HSSFCell.CELL_TYPE_ERROR: // 故障
//System.out.println(" ");
o = " ";
break;
default:
//System.out.print("未知类型 ");
o = " ";
break;
}
} else {
//System.out.print("- ");
o = "- ";
}
if(j == headLineNum) {
data.get(j-headLineNum).set(k, getBottomStringById(dealString,k));
}
if(j > headLineNum) {
data.get(j-headLineNum).set(k, o);
}
}
}
//System.out.println();
}
// System.out.println("*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=");
// for (List<Object> ll : data) {
// for (Object ss : ll) {
// System.err.print(String.valueOf(ss) + " , ");
// }
// System.err.println("*");
// }
}
/**獲得表頭行數*/
private int reflex(String dealString) {
int rows = 1;
TableHeadDeal thd = new TableHeadDeal(dealString);
rows = thd.rows;
return rows;
}
/**獲得表頭底部字串*/
private String getBottomStringById(String dealString, int id) {
String BottomStr = new String();
TableHeadDeal thd = new TableHeadDeal(dealString);
BottomStr = thd.getTableHeadBottomParams().get(id);
return BottomStr;
}
public List<List<Object>> getListDate() {
return data;
}
}
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;
}