Posted by: lrrp | July 4, 2011

Sample code block for Java Date to Timestamp convertion and rounding Bigdecimal values.

Sample code blocks for Java Date to Timestamp convertion and rounding Bigdecimal values to display two decimal points.

package timestampDeciaml;

import java.util.*;
import java.text.*;
import java.sql.Timestamp;

import java.math.BigDecimal;

public class DateToTimestamp {

public DateToTimestamp() {

}

public static void main(String[] args) {

/*Converting  a java Date to TimeStamp*/

try {
String str_date = “2011-07-02 14:51:26”;
DateFormat formatter;
Date date;

formatter = new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);
date = (Date) formatter.parse(str_date);
System.out.println(“Today is ” + date.toString());

java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
System.out.println(“Today is ” + timeStampDate);

} catch (ParseException e) {
System.out.println(“Exception :” + e);
}

/*Different implementations of rounding off BigDecimal values
to display Two Decimal places*/

int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(“123456789.7123456890”);

bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_DOWN);
String output1 = bd.toString();
System.out.println(“output1 123456789.0123456890  ” + output1);

BigDecimal bd3 = new BigDecimal(“123456789.3”);
bd3 = bd3.setScale(decimalPlaces, BigDecimal.ROUND_DOWN);
String output2 = bd3.toString();
System.out.println(“output2 123456789.3 ” + output2);

BigDecimal bd2 = new BigDecimal(3.14159);
bd2 = bd2.setScale(2, BigDecimal.ROUND_HALF_UP);
String output3 = bd2.toString();
System.out.println(“output3 3.14159  ” + output3);

BigDecimal bd4 = new BigDecimal(3.1);
bd4 = bd4.setScale(2, BigDecimal.ROUND_HALF_UP);
String output4 = bd4.toString();
System.out.println(“output2 3.14159  ” + output4);

}

}


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: