Wednesday, October 5, 2011

JAVA: Date and Calendar

This is not something new but something of very common use in most of the projects. In this post I am going to write some date, time and calendar functions that are commonly used as utility. From next time I will copy them from this post rather than code them again.

To get a Date in any Format the SimpleDateFormat Class is used. Following snippet will return current date in provided format in SimpleDateFormat argument.

Date date = new Date();    
DateFormat dateFormatter = new SimpleDateFormat("dd");    
String formattedDate = dateFormatter.format(date);


Format "dd" is used to get the date number from date

Format "yyyy" is used to get the year number from date

Format "MM" is used to get the month number from date

Format "MMMM" is used to get the month name from date

This method will return the date of targeted format from source format.

    String dt = dateString;  // Start date
    SimpleDateFormat sdf = null;
    try {
            sdf = new SimpleDateFormat(sourceFormat);
            Date date = sdf.parse(dt);
    
            sdf  = new SimpleDateFormat(targetFormat);
            dt = sdf.format(date);  // dt is now in the new date format            
    } catch (ParseException e) {
        e.printStackTrace();
    }



To get Number of Days in a Month we will take help from Calendar Class here. Following method will be usd to get number of days in a month.

public static int getNumberOfDaysInMonth(int screenMonth){
      Calendar calendar = Calendar.getInstance();
      int year = Integer.valueOf(getYearNumber());
      int month = screenMonth;
      int date = 1;
      calendar.set(year, month, date);
      int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);        
      
      return days;
}


This method will return Month Name from month number. Calendar is used here as well.

public static String getMonthNameByMonthNumber(int currentMonthNumber) {
    String dt;
    Calendar c = Calendar.getInstance();
    c.set(Calendar.MONTH, currentMonthNumber);
    c.add(Calendar.MONTH, 0);  // number of days to add
    
    SimpleDateFormat sdf  = new SimpleDateFormat("MMMM");
    dt = sdf.format(c.getTime());  // dt is now the new date        
    return dt;
}


To get the First Day of month following method can be used.

public static String getFirstDayOfMonth(int month) {
    Calendar c = Calendar.getInstance();
    c.set(Calendar.MONTH, month);
    c.set(Calendar.DATE, 1);

    DateFormat f = new SimpleDateFormat("EEE");        
    return f.format(c.getTime());
}


Similarly to get the first date of week Calendar Class is used.

public static int getFirstDateOfWeek() {
    Calendar c = Calendar.getInstance();
    c.set(Calendar.WEEK_OF_YEAR, Calendar.WEEK_OF_MONTH);
    c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());

    DateFormat f = new SimpleDateFormat("dd");
    String cc = f.format(c.getTime());

    // Plus 1 is done to get the Monday Date instead of Sunday
    return Integer.valueOf(cc) + 1;
}


There are many other methods that can be used commmonly. I will keep updating this post when ever I got something new. Also do comment If there is any method you want to add here or If any of them can be implemented in much better way.

rizzz86

Sunday, October 2, 2011

Hello Post !


I am writing on this blog after a long time due to some busy schedule from last 4 months. I have switched my job and joined a new software company with in this time frame. Also worked on lots of new tools and technologies that I have to blog on. So lots of topics are in mind to blog and now thinking to give some time to blogging in this busy schedule. I have also completed my MS (Software Engineering) and now looking forward to give some certifications as well.

rizzz86

Monday, March 7, 2011

Dinner at Ambala Corniche

"Ambala" is a newly opened restaurant near sea view - Clifton, Karachi. In comparison with other restaurants on the same street (including Sajjad, Afridi Inn, Hot Bite etc)  "Ambala" is the most well managed and also have a pleasing environment.

Click on the following image to see slideshow by smhumayun.


rizzz86

Monday, February 28, 2011

Split a String with Dot "." in JAVA


In JAVA we can split a String with Dot "." using a split() function. But it can be done in a different way as compared to other characters. Dot "." is a reserved character in regular expression, hence it will not treat the split on dot the same way.

Following code can be used to split a string by dot.

String stringWithDot = "rizzz86.blogspot.com"; 
String[] stringArray = stringWithDot.split("\\.");

Double backslash will do the work where one slash is work as a escape character.

rizzz86

Thursday, January 13, 2011

Iterate over JAVA HashMap in FreeMarker

Java HashMap can be iterated in FreeMarker by using a <#list> tag as follows:

<#list hashMap?keys as key>
        ${key}=${hashMap[key]}
<#list>


If you are using the above code with default FreeMarker Configuration then there would be some different behavior during iteration. For example if the HashMap is:

HashMap hashMap = new HashMap();
hashMap.put("1","one");
hashMap.put("2","two"); 

By iterating on hashMap with default Configuration it will output following keys in result:

put
remove
entrySet
hashCode
productElement
clear
isEmpty
1
values
empty
underlying
productElements
copy
getClass
get
copy$default$1
equals
productPrefix
class
canEqual
keySet
size
2
containsKey
productArity
containsValue
productIterator
toString
putAll        


This result shows that the iteration is done on all the available hashMap properties.

To get rid of this you have to set the FreeMarker Configuration as follows:


Configuration configuration = new Configuration();
BeansWrapper wrapper = (BeansWrapper) this.configuration.getObjectWrapper();
wrapper.setSimpleMapWrapper(true);
this.configuration.setObjectWrapper(wrapper);

Here the BeanWrapper's simpleMapWrapper property is set as 'true'. After setting this configuration the results over iterating on hashMap will give only the defined key-value pair.

rizzz86

Wednesday, January 12, 2011

MD5 Hashing in J2ME

MD5 (Message Digest) is a hashing algorithm that can be used to ensure data integrity, save and protect passwords/codes, generate unique keys of limited length against a long literal etc. It takes input as String and generates the Hash of that string.

In JAVA there is a built-in MD5 support in its Standard Edition (J2SE). But if we talk about its Micro Edition (J2ME) their is no support for MD5. The package of JAVA Standard Edition can also be used in Micro Edition if and only if the platform supports the SATSA-Crypto Optional Package (How to know that your platform supports SATSA-Crypto).

I have found and tested the Third-Party implementation that can generate MD5 hash and can be used in JAVA Micro Edition. You can get the MD5 source files from here.

rizzz86

Wednesday, December 29, 2010

J2ME Default Emulator without asking for Permission

While running J2ME project with Default Emulator it will ask for Permissions in case of File Read/Write, HTTP Connectivity etc. To get rid of this Permission on every access you have to change the Security options of Emulator. In my case I am using NetBeans IDE, so to change these options I will go through following steps:
  1. Open Project Properties
  2. Click on Manage Emulators Button
  3. Go to Tools & Extension Tab and Click Open Preferences Option
  4. On Preferences Window click on Security option
  5. Select Security Policy to 'JTWI'
  6. Select Security Domain as 'trusted'
  7. Now run the project it will not ask for access Permissions

 rizzz86