java creating blank spaces with printf - java

When I run my program, I get this:
run:
Heat Index: Key West, Florida
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
____________________________________________________________________________________________________________________________________
Temperature: 70.3 70.8 73.8 77.0 80.7 83.4 84.5 84.4 83.4 80.2 76.3 72.0
Humidity: 69.0 67.0 66.0 64.0 66.0 69.0 67.0 67.0 70.0 69.0 69.0 70.0BUILD SUCCESSFUL (total time: 0 seconds)
I want to display this so that the months align with each column of numbers, like Jan aligns with the first column of numbers and so on. I know that there are 7 blank spaces between each column of number if the months are aligned. The thing is, I don't know how to create blank spaces, like blank spaces so the months won't show up on top of the Temperature: heading, with printf. Any help will be greatly appreciated.

You need to use System.out.printf() and passing the appropriate flags for the width, see here for the syntax for formatting.
String[] months =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"};
Double[] temper =
{70.3, 70.8, 73.8, 77.0, 80.7, 83.4, 84.5, 84.4, 83.4, 80.2, 76.3, 72.0};
Double[] humid =
{69.0, 67.0, 66.0, 64.0, 66.0, 69.0, 67.0, 67.0, 70.0, 69.0, 69.0, 70.0};
System.out.printf(" %7s%7s%7s%7s%7s%7s%7s%7s%7s%7s%7s%7s\n",
(Object[])months);
System.out.printf("________________________________________"
+ "________________________________________________________\n");
System.out.printf("Temperature:%7.1f%7.1f%7.1f%7.1f%7.1f"
+ "%7.1f%7.1f%7.1f%7.1f%7.1f%7.1f%7.1f\n",
(Object[])temper);
System.out.printf(" Humidity:%7.1f%7.1f%7.1f%7.1f%7.1f"
+ "%7.1f%7.1f%7.1f%7.1f%7.1f%7.1f%7.1f\n",
(Object[])humid);

try this.. you can specify spaces between each print..
String[] day = {"Sun", "Mon", "Tues", "Friday","Saturday"};
for(String s :day){
System.out.printf("%15s", s);
}

This will print exactly four spaces plus the three taken up by the month. Also, if you just want to print Strings you don't really need printf. Below are two options.
System.out.printf(" %s", month);
or
System.out.print(" " + month);
I would also recommend coming up with a way to do this without hard coding the spaces. Maybe set up a loop to print spaces which can change the width.

try this
System.out.println("\n");

Related

What is the way to get a list of options that can be selected from a dropdown using Selenium and Java?

I want to get a list of all the options that can be selected from a dropdown menu in selenium using java. How can I do that?
Use this method
getAllSelectedOptions()
Refer this site for more information
https://www.codota.com/code/java/methods/org.openqa.selenium.support.ui.Select/getAllSelectedOptions
There are multiple approaches to print the texts from the option elements of a drop-down-menu. Ideally while interacting with a html-selct you need to use the Select Class. Further to interact with all the <option> tags you need to use getOptions() method. As an example to print the texts from the Day, Month and Year option elements within facebook landing page https://www.facebook.com/ you you need to use WebDriverWait for the elementToBeClickable() and you can use the following Locator Strategies.
Options from Day Dropdown using id attribute:
WebElement dayElement = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.id("day")));
Select selectDay = new Select(dayElement);
List<WebElement> dayList = selectDay.getOptions();
for (int i=0; i<dayList.size(); i++)
System.out.println(dayList.get(i).getText());
Options from Month Dropdown using xpath and java-8 stream() and map():
Select selectMonth = new Select(new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//select[#id='month']"))));
List<String> myMonths = selectMonth.getOptions().stream().map(element->element.getText()).collect(Collectors.toList());
System.out.println(myMonths);
Console Output:
[Month, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sept, Oct, Nov, Dec]
Options from Month Dropdown using [tag:css_selectors] and java-8 stream() and map() in a single line of code:
System.out.println(new Select(new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("select#year")))).getOptions().stream().map(element->element.getText()).collect(Collectors.toList()));
Console Output:
[Year, 2020, 2019, 2018, 2017, 2016, 2015, 2014, 2013, 2012, 2011, 2010, 2009, 2008, 2007, 2006, 2005, 2004, 2003, 2002, 2001, 2000, 1999, 1998, 1997, 1996, 1995, 1994, 1993, 1992, 1991, 1990, 1989, 1988, 1987, 1986, 1985, 1984, 1983, 1982, 1981, 1980, 1979, 1978, 1977, 1976, 1975, 1974, 1973, 1972, 1971, 1970, 1969, 1968, 1967, 1966, 1965, 1964, 1963, 1962, 1961, 1960, 1959, 1958, 1957, 1956, 1955, 1954, 1953, 1952, 1951, 1950, 1949, 1948, 1947, 1946, 1945, 1944, 1943, 1942, 1941, 1940, 1939, 1938, 1937, 1936, 1935, 1934, 1933, 1932, 1931, 1930, 1929, 1928, 1927, 1926, 1925, 1924, 1923, 1922, 1921, 1920, 1919, 1918, 1917, 1916, 1915, 1914, 1913, 1912, 1911, 1910, 1909, 1908, 1907, 1906, 1905]
This approch might help you to get understand how to get all selectable options from dropdown
driver.navigate().to("https://the-internet.herokuapp.com/");
WebDriverWait wait = new WebDriverWait(driver,10,100);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[#href='/dropdown']"))).click();
WebElement element = driver.findElement(By.xpath("//select[#id='dropdown']"));
Select select = new Select(element);
List<WebElement>allOptions = select.getOptions();
allOptions.forEach(value->{System.out.println(value.getText());});

Push Mysql table contents (returned rows of sql query) into java hashmap

I have Mysql table and I want to push returned values from query into java hashmap.
I am very beginner in java. I took some help from available answers and wrote a code.
Summary: I have list of country codes as connectedCountryList =[40,203,250,528] which should be the Key of the hashmap
and I want to iterate over these country codes and store return values from sql table which has milions of rows.
Mysql table sample data looks like-
utc date area_in area_out value
2015-12-05T03:00Z 05.12.2015 03:00 276 40 3059
2015-12-04T03:00Z 04.12.2015 03:00 276 40 2523
2015-12-07T03:00Z 07.12.2015 03:00 276 40 2873
2015-12-06T03:00Z 06.12.2015 03:00 276 40 3386
2015-12-01T03:00Z 01.12.2015 03:00 276 40 2936
2015-12-03T03:00Z 03.12.2015 03:00 276 40 2564
2016-04-01T19:00Z 01.04.2016 19:00 276 203 -291
2016-05-02T05:00Z 02.05.2016 05:00 276 203 -276
2016-05-03T05:00Z 03.05.2016 05:00 276 203 -123
2016-04-03T19:00Z 03.04.2016 19:00 276 203 -899
2016-04-02T19:00Z 02.04.2016 19:00 276 203 -1100
2016-05-01T05:00Z 01.05.2016 05:00 276 203 -45
2015-01-16T13:00Z 16.01.2015 13:00 276 203 -339
2016-04-05T19:00Z 05.04.2016 19:00 276 203 734
2015-01-17T13:00Z 17.01.2015 13:00 276 203 -300
2017-04-27T19:00Z 27.04.2017 19:00 276 250 -75
2016-09-25T23:00Z 25.09.2016 23:00 276 250 -174
2015-03-18T12:00Z 18.03.2015 12:00 276 250 338
2016-10-11T09:00Z 11.10.2016 09:00 276 250 1093
2015-03-17T12:00Z 17.03.2015 12:00 276 250 190
2017-05-24T05:00Z 24.05.2017 05:00 276 250 -454
2015-03-14T03:00Z 14.03.2015 03:00 276 528 3336
2016-05-09T00:00Z 09.05.2016 00:00 276 528 2705
2016-11-12T19:00Z 12.11.2016 19:00 276 528 3030
2015-03-15T03:00Z 15.03.2015 03:00 276 528 3182
2016-10-15T05:00Z 15.10.2016 05:00 276 528 2111
Actually I have big code and this is a small part I am working on it.
connectedCountryList =[40,203,250,528];
String tablename= "mytable";
MarketAreacode = "276"
public class Exchangeflows{
private String utc;
private int value;
public Exchangeflows(){}
public Exchangeflows(String utc,int value ){
this.utc =utc;
this.value=value;
}
public String getutc(){
return utc;
}
public void setutc(String UTC) {
this.utc = UTC;
}
public int getvalue(){
return value;
}
public void setvalue(int value) {
this.value = value;
}
}
final Map<Integer, Exchangeflows> CbExchangePower = new HashMap<Integer, Exchangeflows>();
for (final Integer countryCode : connectedCountryList) {
final String sqlquery = "select * from " + tableName +" where ((area_in = '" + marketAreaCode +"' "+" and area_out in ('"+countryCode+"'))"+
"or (area_out = '"+marketAreaCode+"' "+"and area_in in ('" + countryCode +"'))) order by utc ASC ";
conn.setResultSet(sqlquery);
// SQL query Executes perfect
while (conn.resultSet.next()){
String utc = conn.resultSet.getString("utc");
int value = conn.resultSet.getInt("value");
PowerExchange = new Exchangeflows (utc, value);
CbExchangePower.put(countryCode,PowerExchange);
}
When I run my code it reads data correclty in each iteration but every time it overwrites the values and I am getting latest values according to UTC ASC as per sql query. e.g. [2015-12-07T03:00Z 07.12.2015 03:00 276 40 2873 ]. I do not understand how I should iterate my sql in a loop to save all content of table into hashmapin the form of <countryCode <utc, value>>. The hashmap sould iterate through list of countries, hence country code will be unique in each iteration as per for loop and have to add each row from sql table in while loop.
Can any one suggest me any changes in my code?
To avoid the overwriting you can swap the key-values with each other. So, your Hashmap would be CbExchangePower<Exchangeflows, Integer> and then to put the values from DB by CbExchangePower.put(PowerExchange,countryCode).
In order to read the Map according to the values, you can perform like following:
Map<Integer, List<Exchangeflows>> countryCodes = new HashMap<Integer, List<Exchangeflows>>();
for(Entry<Exchangeflows,Integer> entry : CbExchangePower.entrySet()){
List<Exchangeflows> list = new ArrayList<Exchangeflows>();
if(countryCodes.containsKey(entry.getValue()))
list = countryCodes .get(entry.getValue());
list.add(entry.getKey());
countryCodes .put(entry.getValue(), list);
}
System.out.println(countryCodes);
This should be able to print the list with the desired values of yours.
Behavior of hashmap is that if you try to insert the same key again then the value will be overridden.
I am not still clear on your requirement. Do you want to store the country code as key and the value as list from the sql output.
eg:
40 2015-12-05T03:00Z 3059
2015-12-04T03:00Z 2523
more or less like grouping UTC and value by country code.
Here's the pseudocode code which you have to implement:
1. Loop through country code list.
2. Use stringbuffer to form the country code as comma separated values.
3. Pass the string to SQL query.
4. Iterate through the resultset.
5. Pass the country code in CbExchangePower and get the value.
6. If the value is null then
create a new list and add PowerExchange object
else
create a new PowerExchange object and add it to the existing list

Loop prints last line multiple time - What am I doing wrong? - Using BufferedReader

This is an assignement for school.
One part of my assignment is to read from a file with 15 elements, store each object in an array and printing the corrected objects in a new file.
Each object has 6 elements in them, separated with a space. So I use a switch case to determine what element is recorded when:
example: space 0 is a Long, space 1 is a String, space 2 is an int, etc.
Here are the elements in the .txt file
900876512 Core_Java 2007 Mike_Simon 129.99 568
765867999 Java_Applications_for_Programmers 2010
David_Wilson_and_Jack_Westman 173.25 672
465979798 From_Java_to_C++ 2008 Linda_Jackson 118.73 439
760098908 Microsoft_VC++ 2006 Garry_Wesley 165.20 416
529086890 Software_Engineering 2005 Alain_Macmillan 219.99 651
765867999 Visual_Basic 2004 Mary_Rosen 108.33 388
529086890 Database_Systems 2007 Peter_Jones_and_Jack_Lewis 157.87 862
800003243 VLSI 2008 Martha_Niclson 117.29 360
200900210 C_# 2007 D._Smith 109.99 387
200900210 Cellular_Communications 2010 Jones_Tomson 127.87 162
542087665 Pattern_Recognition 1998 Sam_Davis 212.59 328
900876512 Programming_Methodologies 2009 Steve_A._Richmond 182.95 590
900876512 OO_Programming 2008 Frank_Raymond 182.25 439
900876512 Design_Pattern 2002 Jay_Franklin 122.15 217
900876512 Networking_and_Data_Communications 2010 Pete_Jonson 229.25 724
The problem is that, the loop prints all the object fine if I am inside the J loop. But once outside, if I print the array it will print the last line multiple times like this:
900876512 Networking_and_Data_Communications 2010 Pete_Jonson 229.25 724
900876512 Networking_and_Data_Communications 2010 Pete_Jonson 229.25 724
900876512 Networking_and_Data_Communications 2010 Pete_Jonson 229.25 724
900876512 Networking_and_Data_Communications 2010 Pete_Jonson 229.25 724
900876512 Networking_and_Data_Communications 2010 Pete_Jonson 229.25 724
900876512 Networking_and_Data_Communications 2010 Pete_Jonson 229.25 724
900876512 Networking_and_Data_Communications 2010 Pete_Jonson 229.25 724
900876512 Networking_and_Data_Communications 2010 Pete_Jonson 229.25 724
900876512 Networking_and_Data_Communications 2010 Pete_Jonson 229.25 724
900876512 Networking_and_Data_Communications 2010 Pete_Jonson 229.25 724
900876512 Networking_and_Data_Communications 2010 Pete_Jonson 229.25 724
900876512 Networking_and_Data_Communications 2010 Pete_Jonson 229.25 724
900876512 Networking_and_Data_Communications 2010 Pete_Jonson 229.25 724
900876512 Networking_and_Data_Communications 2010 Pete_Jonson 229.25 724
900876512 Networking_and_Data_Communications 2010 Pete_Jonson 229.25 724
I tried to put
PublicationArray[i] = obj_publication; in different places, but nothing works.
For what I saw, each line is read and stored in the array, but then it is override by the next iteration of the loop.
Instead of doing
i[0]j[0]
i[0]j[1]
i[0]j[2]
etc.
it is doing something like this:
i[0]j[0]
i[1]j[0]
i[2]j[0]
etc.
I understand loops but I have no idea what's wrong in this code.
This is an assignment for school, so I have specific things I can and can't do. For example, I can't use Arraylist. Only an array.
This is only a small part of my code, if something isn't clear please tell me so I can fix it. I've been staring at it for so long I know it by heart so I have difficulties seeing from a fresh point of view.
I have created BufferReader and PrintWriter in a try catch around this code. The BufferReader and PrintWriter are closed outside the loop.
EDIT: So I tried to print index of i and j like #Jernej K said but everything seems fine there.
EDIT 2: I thought the problem was my Output method but I realized it was in the loop the problem. When I use System.out.println(PublicationArray[i].toString); inside the j loop I have a different result than if I am using System.out.println(PublicationArray[i].toString); inside the i loop.
//******************************readline() in files*********************
//holding array...
//this works, prints everything ok.
String[] myHolder = new String[iNumberOfItems];
for(int i=0; i < iNumberOfItems; i++){
myHolder[i] = myReader.readLine();
System.out.println("holder "+myHolder[i].toString());
}
//this is the problem...
for(int i=0; i < iNumberOfItems; i++){
sContainer = myHolder[i];
sContainer = sContainer.replace('\t', ' ');//replace all tabs with spaces
if(sContainer == null){
return;//exit the loop if this read, shouldn't do it but just in case!
}
else{//if there is a line
iCountSpace = 0;//reset space count for each line
//******************read each char in the line*********************
for(int j=0; j < sContainer.length(); j++){
cTemp = sContainer.charAt(j); //read one character at a time
//***********switch case-->what publication type needs to be recorded?
//iCountSpace check at which space the read() is -> if space new space, iCountSpace++
switch(iCountSpace){
case 0:// case 0 space is Long publication_code
sTemp.append(cTemp);//concatenation
//if the char is a space
if(cTemp == cSpace){
sTemp.deleteCharAt(sTemp.length()-1);//remove the space
sSwitchTypeContainer = sTemp.toString(); //1-->StringBuffer converting to String
code = Long.valueOf(sSwitchTypeContainer);//2-->Value of the String converted into a Long
obj_publication.setCode(code);//3-->value of long placed in code
iCountSpace ++;//4-->increase value of the space number
sTemp.delete(0, sTemp.length());//4--empty the StringBuffer for next element
}
break;
case 1://case 1 space is String publication_names
sTemp.append(cTemp);//concatenation-->casting because we are recording a String
if(cSpace == cTemp){//if the char is a space, remove it
sTemp.deleteCharAt(sTemp.length()-1);//remove the space
obj_publication.setName(sTemp.toString());//transform the StringBuffer to String
iCountSpace ++;//increase value of the space number
sTemp.delete(0, sTemp.length());//reset sTemp
}
break;
case 2://case 2 space is int publication_year
sTemp.append(cTemp);//concatenation
if(cSpace == cTemp){//if iTemp is a space...remove it
sTemp.deleteCharAt(sTemp.length()-1);//remove the space
sSwitchTypeContainer = sTemp.toString();//1-->converting StringBuffer to String
iPublication = Integer.valueOf(sSwitchTypeContainer);//2-->converting String to int
obj_publication.setYear(iPublication);//3-->set year
iCountSpace++;//4-->increase space number
sTemp.delete(0, sTemp.length());//5-->clear the buffer String
}
break;
case 3://case 3 space is String publication_authorname
sTemp.append(cTemp);//concatenation-->string
if(cSpace == cTemp){//if cTemp is a space...
sTemp.deleteCharAt(sTemp.length()-1);//remove the space
obj_publication.setAuthorName(sTemp.toString());//-->set the string in the object
iCountSpace++;//-->increase space
sTemp.delete(0, sTemp.length());//clear buffer String
}
break;
case 4://case 4 space is double publication_cost
sTemp.append(cTemp);//concatenation
if(cSpace == cTemp){//if iTemp is a space
sTemp.deleteCharAt(sTemp.length()-1);//remove the space
sSwitchTypeContainer = sTemp.toString();//1-->converting StringBuffer to String
dCost = Double.valueOf(sSwitchTypeContainer);//2-->converting String to Double
obj_publication.setCost(dCost);//3-->recording variable in object
iCountSpace++;//4-->increase space number
sTemp.delete(0, sTemp.length());//-->reset value of sTemp String Buffer
}
break;
case 5://case 5 space is int publication_nbpages
sTemp.append(cTemp);//concatenation
if(j == (sContainer.length()-1)){//if it's the last char of the line
sSwitchTypeContainer = sTemp.toString();
iPublication = Integer.valueOf(sSwitchTypeContainer);
obj_publication.setPages(iPublication);
iCountSpace++;
sTemp.delete(0, sTemp.length());
}
break;
default:
break;
}//end of switch case
}//end of for loop J
PublicationArray[i] = obj_publication;
}//end of else
}//end of foor loop i
RESOLVED!
updating my post because of #Servy comment
I was using one object as a container. Then I was updating it's value and placing it in the array.
I thought I was creating multiple objects but since it was the same reference, it was updating ALL the objects placed in the array.
In other words, instead of creating multiple objects with their own reference I created multiple references to one object.
I added a loop to create empty objects in the array:
Publication[] PublicationArray = new Publication[iSize];
for(int i=0; i<iNumberOfItems; i++){
PublicationArray[i] = new Publication();
}
Instead of setting the object like this: obj_publication.setName(String) I needed to do something like that PublicationArray[i].setName(String)
Voilà! My headache is gone.

Displaying Data in a Table Android Development?

Working on my first app for android and want to display some data in a table(or something similar). After looking around here I guess android does not support something like a JTable; someone said you have to create a custom table? What is the best way to display data that is a string in CSV format? In a Java app I created I have a function that creates a 2D Array out of the string and throws that into a JTable.
Data Format in String:
Sun 02-16-14 09:45 PM,1,REAL TIRED,JUST WACK AT IT,2 - 4,
Sun 02-23-14 08:10 PM,1,BALLERS,REAL TIRED,4 - 11,
Sun 03-02-14 09:00 PM,1,REAL TIRED,EL TRI,1 - 7,
Sun 03-09-14 05:50 PM,1,GO GO POWER RANGERS,REAL TIRED,4 - 9,
Sun 03-16-14 06:40 PM,1,REAL TIRED,GAME OF GROANS,16 - 0,
Sun 03-23-14 09:00 PM,1,HUNGOVER HAT TRICKS,REAL TIRED,
Sun 03-30-14 07:25 PM,1,REAL TIRED,PRESTIGE WORLD WIDE,
Sun 04-06-14 04:20 PM,1,REAL TIRED,BALLERS,
Not sure if there are any good options because of the limited space for mobile devices. Maybe only display one row at a time and be able to click through them?
You can try this example, you will be very comfortable with this code. Even though if you want to add rows in the table view dynamically from an server or from an API call then just create a for loop and add it according this example.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
String[] presidents = { "Dwight D. Eisenhower", "John F. Kennedy",
"Lyndon B. Johnson", "Richard Nixon", "Gerald Ford",
"Jimmy Carter", "Ronald Reagan", "George H. W. Bush",
"Bill Clinton", "George W. Bush", "Barack Obama",
"Dwight D. Eisenhower", "John F. Kennedy", "Lyndon B. Johnson",
"Richard Nixon", "Gerald Ford", "Jimmy Carter",
"Ronald Reagan", "George H. W. Bush", "Bill Clinton",
"George W. Bush", "Barack Obama", "Dwight D. Eisenhower",
"John F. Kennedy", "Lyndon B. Johnson", "Richard Nixon",
"Gerald Ford", "Jimmy Carter", "Ronald Reagan",
"George H. W. Bush", "Bill Clinton", "George W. Bush",
"Barack Obama" };
ScrollView scrollView = new ScrollView(this);
TableLayout tableLayout = new TableLayout(this);
for (int i = 0; i < presidents.length; i++) {
TableRow tableRow = new TableRow(this);
TextView tv = new TextView(this);
tv.setPadding(10, 10, 10, 10);
tv.setGravity(Gravity.CENTER);
tv.setText(presidents[i]);
tableRow.addView(tv);
tableLayout.addView(tableRow);
View v = new View(this);
v.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT, 1));
v.setBackgroundColor(Color.rgb(51, 51, 51));
tableLayout.addView(v);
}
scrollView.addView(tableLayout);
setContentView(scrollView);
}
}
Hope so you would like this. If this is suitable to you then please mark as accepted answer so that it could be helpful for others.

Converting to and from Hindu calendar

How can I convert unix time to Hindu calendar­Wikipedia time and the other way round in php, Perl or Python or Java? I know I can convert to Hebrew and Jewish. But Hindu is not an option.
To be more specific, I'm talking about the Hindu lunar calendar. The following website is working and does exactly what I want: http://web.meson.org/calendars/. For example, it 'translates' 28-1-2012 (Gregorian) to 5-11-2068 (Hind. Lun.). How can I accomplish the same task? And if there are absolutely no scrips out there, how can I write it myself?
Did you check DateTime-Indic-0.1 family of modules? At least DateTime::Indic::Chandramana
seems to have a method to convert traditional date into UTC values (utc_rd_values).
UPDATE:
I suppose Calendar::Saka may be useful as well for many users (as I have known, it's the Indian national calendar), in particular, to_gregorian() and from_gregorian() methods.
For Python, use calendar2 (note: this is not the built-in calendar module).
Sample use:
>>> from calendar2 import *
>>> old_hindu_solar_from_absolute(absolute_from_gregorian(3,1,2012))
(11, 16, 5112)
>>> old_hindu_lunar_from_absolute(absolute_from_gregorian(3,1,2012))
(12, 0, 8, 5112)
Paper: Indian Calendrical Calculations
Provides Common Lisp code in the appendix.
While a Python (or other language) solution could be written according to the paper, the authors enumerate the Indian calendar rules pretty well, so it's a pretty solid paper if you're willing to consider taking the provided Common Lisp code.
Seems to be a difficult task. According to this discussion at bytes.com there is no clear way to accomplish a 100% correct conversion. But it seems that they are wrong when they assume that the Hindu calendar has only 364 days instead of 365 (or 366 in leap years).
Here you can find a good conversion table including the handling of leap years: http://hinduism.about.com/od/basics/a/monthsdayseras.htm
If it is as easy as written there you can try something like this (php code):
<?php
function convertDateToHinduDate($date) {
$beginningDayOfMonth = array(
1 => 21,
2 => 20,
3 => 22 + (dateIsLeapYear($date) ? -1 : 0), /* 21 in leap years */
4 => 21,
5 => 22,
6 => 22,
7 => 23,
8 => 23,
9 => 23,
10 => 23,
11 => 22,
12 => 22,
);
$daysOfHinduMonth = array(
1 => 30 + (dateIsLeapYear($date) ? 1 : 0), /* 31 in leap years */
2 => 31,
3 => 31,
4 => 31,
5 => 31,
6 => 31,
7 => 30,
8 => 30,
9 => 30,
10 => 30,
11 => 30,
12 => 30,
);
$day = (int) date('d', strtotime($date));
$month = (int) date('m', strtotime($date));
$year = (int) date('Y', strtotime($date));
$monthBefore = $day < $beginningDayOfMonth[$month];
$yearBefore = $month < 3 || ($month == 3 && $day < $beginningDayOfMonth[3]);
$newYear = $year + 57 + ($yearBefore ? -1 : 0);
$newMonth = $month - 2 + ($monthBefore ? -1 : 0);
if($newMonth < 1) $newMonth = 12 + $newMonth;
$newDay = $day - $beginningDayOfMonth[$month];
if($newDay < 1) $newDay = $daysOfHinduMonth[$newMonth] + $newDay;
return date("d-m-Y", mktime(11, 59, 0, $newMonth, $newDay, $newYear));
}
function dateIsLeapYear($date) {
return date('L', strtotime($date));
}
$date = date("d-m-Y", strtotime('2012-01-28'));
echo 'Date: ', $date, ' (is leap year: ', dateIsLeapYear($date) ? 'yes' : 'no', ')<br />';
echo 'Converted Hindu date: ', convertDateToHinduDate($date);
?>
Output of this code:
Date: 28-01-2012 (is leap year: yes)
Converted Hindu date: 07-11-2068
But according to the calculator of this Java applet, it should be 05-11-2068 instead of 07-11-2068. So, there are still some conversion rules missing. Maybe you can give me some more information so that i can correct the code above.
I dont know whether it is correct approach or not but
Please go to http://calendarhome.com/converter/ site and download two javascript files astro.js and calendar.js and follow onchange events of Gregorian Date and fetch Indian Civil Date parameters.

Categories