Convert DateTime from UTC to EST in .Net 3.0 - c#-3.0

I am using .Net 3.0 and I want to convert a DateTime value from UTC to EST/EDT (need Daylight savings incorporated too).
I understand that this would be straight-forward to achieve using .Net 3.5, with the help of TimeZoneInfo class. I do not want to use Timezone.CurrentTimeZone because I want this value converted to EST/EDT irrespective of the timezone of the local computer. Unfortunately switching to 3.5 is not an option. Search on the internet revealed options of using system registry and stuff.
Is there an easier way of doing this?
Could anyone please lead me in the right direction and let me know the options to achieve this?

The following function determines whether a particular DateTime object represents Daylight Saving Time in the Eastern Time Zone.
public static bool IsEasternDaylightTime(DateTime dt){
// Find out whether it's Daylight Saving Time
dt=dt.AddHours(-5); // Convert to Eastern Standard Time
if(dt.Year<=2006){
// 2006 and earlier
if(dt.Month<=3 || dt.Month>=11){
// Standard Time
return false;
} else if(dt.Month>=5 && dt.Month<=9){
// Daylight Time
return true;
} else if(dt.Month==4){
// find the first Sunday of April
int firstSunday=1;
while(new DateTime(dt.Year,dt.Month,firstSunday).DayOfWeek!= DayOfWeek.Sunday){
firstSunday++;
}
if(dt.Day<firstSunday)
return false;
else if(dt.Day>firstSunday)
return true;
else {
// DST begins at 2AM
if(dt.Hour<2)
return false; // Standard Time
else if(dt.Hour>=3)
return true; // Daylight Time
else
return false; // Ambiguous Time
}
} else {
// find the last Sunday of October
int lastSunday=1;
for(int i=1;i<=31;i++){
if(new DateTime(dt.Year,dt.Month,i).DayOfWeek== DayOfWeek.Sunday){
lastSunday=i;
}
}
if(dt.Day<lastSunday)
return true;
else if(dt.Day>lastSunday)
return false;
else {
// DST ends at 2AM
if(dt.Hour<1)
return true; // Daylight Time
else if(dt.Hour>=2)
return false; // Standard Time
else
return false; // Standard Time
}
}
} else {
// 2007 and later
if(dt.Month<=2 || dt.Month>=12){
// Standard Time
return false;
} else if(dt.Month>=4 && dt.Month<=10){
// Daylight Time
return true;
} else if(dt.Month==3){
// find the second Sunday of March
int sundays=0;
int lastSunday=1;
for(int i=1;i<=31;i++){
if(new DateTime(dt.Year,dt.Month,i).DayOfWeek== DayOfWeek.Sunday){
lastSunday=i;
sundays++;
if(sundays==2)break;
}
}
if(dt.Day<lastSunday)
return false;
else if(dt.Day>lastSunday)
return true;
else {
// DST begins at 2AM
if(dt.Hour<2)
return false; // Standard Time
else if(dt.Hour>=3)
return true; // Daylight Time
else
return false; // Ambiguous Time
}
} else {
// find the first Sunday of November
int firstSunday=1;
while(new DateTime(dt.Year,dt.Month,firstSunday).DayOfWeek!= DayOfWeek.Sunday){
firstSunday++;
}
if(dt.Day<firstSunday)
return true;
else if(dt.Day>firstSunday)
return false;
else {
// DST ends at 2AM
if(dt.Hour<1)
return true; // Daylight Time
else if(dt.Hour>=2)
return false; // Standard Time
else
return false; // Standard Time
}
}
}
}
With this function, you can convert the given DateTime accordingly. Example:
// dateTime is assumed to be in UTC, not local time
bool dst=IsEasternDaylightTime(dateTime);
if(dst)
dateTime=dateTime.AddHours(-4);
else
dateTime=dateTime.AddHours(-5);

Related

Error informing a Timestamp field which comes from a file .parquet

I'm trying to inform a Timestamp field with the date when I get it, I compile the code but it shows me a Nullpointer.
public class SkeletonTransform implements Transform {
#Override
public Map<String, Dataset<Row>> transform(Map<String, Dataset<Row>> map) {
Dataset<Row>dataset = map.get("TINCLDBC");
SparkSession s= dataset.sparkSession();
Date nowDate = Date.valueOf(LocalDate.now());
dataset.withColumn("GF_AUDIT_DATE",
when(col("GF_AUDIT_DATE").isNull(), nowDate)
.otherwise(col("GF_AUDIT_DATE")));
if(!"true".equalsIgnoreCase(InputParams.get("COMPLETE")) && map.get("CONTROL_DATE") != null){
Dataset<Date> ds_fec =map.get("CONTROL_DATE").as(Encoders.DATE());
if (ds_fec !=null && !ds_fec.isEmpty()){
Date date = ds_fec.collectAsList().get(0);
dataset = dataset.filter(dataset.col("GF_AUDIT_DATE").geq(date));
}
}
return map;
}
}

Retrive Data using by $or and $and from two MongoDB collectionDa

What i am trying to do is display the response from a POST message on to the HTML loaded in my webview. However, the my webview appears blank. I can see the response message by in LogCat by printing it out. However, again my webview appears blank. Example.html is the page loading in my webview. My implementation is below:
private void startSchedule()
{
for(int i=0;i<temPojoData.size();i++)
{
tempPojo tem =temPojoData.get(i);
/////////////////////// Daily and AllDays functionality start here //////////////////
if(tem.getDaysweekmonth().equals("Daily") )
{
if(tem.getDaysbases().equals("AllDays")) {
if (findDateBTwoDates(tem.getStartDate(), tem.getEndDate())) {
Log.i("Daily Date", "Today Available");
layoutID += tem.getLayout();
}
}else if(tem.getDaysbases().equals("Whole Day")){
}else if(tem.getDaysbases().equals("Morning"))
{ scheduleStartTimes.add(tem.getStartTime());
}else if(tem.getDaysbases().equals("After Noon"))
{ scheduleStartTimes.add(tem.getStartTime());
}else if(tem.getDaysbases().equals("Evening"))
{ scheduleStartTimes.add(tem.getStartTime());
}else if(tem.getDaysbases().equals("Night"))
{ scheduleStartTimes.add(tem.getStartTime());
}else if(tem.getDaysbases().equals("Choose Time"))
{ scheduleStartTimes.add(tem.getStartTime());
}
}
/////////////////////// Weekly and AllDays functionality start here //////////////////
else if(tem.getDaysweekmonth().equals("weekly") && tem.getDaysbases().equals("AllDays"))
{
if(tem.getDaysbases().equals("AllDays")) {
}
}
/////////////////////// Monthly and AllDays functionality start here //////////////////
else if(tem.getDaysweekmonth().equals("montly") && tem.getDaysbases().equals("AllDays"))
{
if(tem.getDaysbases().equals("AllDays")) {
}
}
}
}
private void findTimeBTwoTimes(String sTime,String eTime)
{
try {
String string1 = "20:11:13";
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
String string2 = "14:49:00";
Date time2 = new SimpleDateFormat("HH:mm:ss").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
String someRandomTime = "01:00:00";
Date d = new SimpleDateFormat("HH:mm:ss").parse(someRandomTime);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);
calendar3.add(Calendar.DATE, 1);
Date x = calendar3.getTime();
if (x.after(calendar1.getTime()) && x.before(calendar2.getTime())) {
//checkes whether the current time is between 14:49:00 and 20:11:13.
System.out.println(true);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
private boolean findDateBTwoDates(String sDate,String eDate)
{
try {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String s = sDate.replace(" AM","");
String e = eDate.replace(" AM","");
String oeStartDateStr =sDate.replace("PM","");
String oeEndDateStr =eDate.replace("PM","");
Log.i("Start End Date ",sDate+"------------"+eDate);
Calendar cal = Calendar.getInstance();
Integer year = cal.get(Calendar.YEAR);
Date startDate = sdf.parse(oeStartDateStr);
Date endDate = sdf.parse(oeEndDateStr);
Date d = new Date();
String currDt = sdf.format(d);
if ((d.after(startDate) && (d.before(endDate))) || (currDt.equals(sdf.format(startDate)) || currDt.equals(sdf.format(endDate)))) {
System.out.println("Date is between 1st april to 14th nov...");
return true;
}
/*else {
System.out.println("Date is not between 1st april to 14th nov...");
}*/
}catch (Exception e){}
return false;
}
I will explain this in a sudo code so that you can come up with a solution.
The first point to your answer is that -> No, you cannot do it in a straightforward manner. The reason behind this is that MongoDB does not have/support joins. Like in SQL where you can join two tables and query them for conditional results; the same is not doable in MongoDB.
But do not lose hope. You cannot do a join on the DB side but you can certainly come up with a solution on the driver/application side. What I would suggest you to do is as follows. (I am using the JAVA driver and Morphia so my solutions' arrangement may look specific to them)
Have a DAO interface for both collections seperately
public interface MyDAO1 extends DAO<MyClass1, ObjectId>
{
public MyClass1 getByName(String name);
}
public interface MyDAO2 extends DAO<MyClass2, ObjectId>
{
public MyClass2 getByResult(int result);
}
First make implementation classes for both the above interfaces. That's pretty simple so I am skipping it to move on to the real part. Have an implementation of the interface
public class MyDAOImpl extends BasicDAO<MyClass, ObjectId> implements MyDAO1, MyDAO2
{
public MyClass1 getByName (String name)
{
MyClass1 output= query collection1 with with the Name;
return output;
}
public MyClass2 getByResult (int result)
{
MyClass2 output= query collection2 with with the result;
return output;
}
public void getByNameResult (String name, int result)
{
MyClass1 output1 = getByName (name);
MyClass2 output2 = getByResult (result);
print them in however format you want OR create a string;
}
}
please note:
MyClass1 is the #Entity class for the employee collection
MyClass2 is the #Entity class for the result collection

Next day check by using calendar JSF primefaces

i am working on a requirement. what i need to do is to retreieve the last enetered date from database, increment it and then check if the day is saturday or not.
the part i am stuck at is how to check if the next day is saturday i am using primefaces 3.5 jsf2.1 apache tomcat 7.0.39
FacesContext context = FacesContext.getCurrentInstance();
Map requestMap = context.getExternalContext().getRequestParameterMap();
String value = (String) requestMap.get("id");
Integer id = Integer.parseInt(value);
SimpleDateFormat sdf= new SimpleDateFormat();
String sector=new String();
setFund(new Fund());
for(Map row:fund_grid){
Integer edit_id=(Integer.parseInt((String) row.get("fund_id")));
if(id.equals(edit_id)){
sector=(String) row.get("fund_sector_label");
mfp.setFund_id(Integer.parseInt( (String) row.get("fund_id")));
fund.setFund_id( (String) row.get("fund_id"));
setValidity_date(request_invoker.select_validity_date());
try {
Date ndate=sdf.parse((String) getValidity_date().get(0).get("validitydate"));
// Date is here retireved from database value 15-11-2013
//now incrementing for a day
Calendar c = Calendar.getInstance();
c.setTime(ndate);
c.add(Calendar.DATE, 1);
fund.setNav_entry_date(c.getTime());
//here is where i am stuck i dont know how to check whether date is of saturday or not
if(fund.getNav_entry_date().equals(Calendar.SATURDAY))
{
c.add(Calendar.DATE, 2);
fund.setNav_entry_date(c.getTime());
}
else
{
fund.setNav_entry_date(c.getTime());
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
RequestContext context2 = RequestContext.getCurrentInstance();
if(sector.equals("open-end")){
context2.execute("opendialog.show();");
}
else if(sector.equals("close-end")){
context2.execute("closedialog.show();");
}
else if(sector.equals("pension")){
context2.execute("pensiondialog.show();");
}
}
any help much appreciated
Made changes to the bean and it works calendar c has the date from database and d has the curret date.
Calendar c = Calendar.getInstance();
c.setTime(ndate);
Calendar d=Calendar.getInstance();
if(d.get(Calendar.DATE)==(c.get(Calendar.DATE)))
{
//message here
FacesMessage msg = new FacesMessage("NAV Upto Date" , "NAV Upto Date");
FacesContext.getCurrentInstance().addMessage(null, msg);
break;
}
else
{
c.add(Calendar.DATE, 1);
int day=c.SATURDAY;
int week=c.get(Calendar.DAY_OF_WEEK);
if(day==(week))
{
c.add(Calendar.DATE, 2);
fund.setNav_entry_date(c.getTime());
mfp.getDc().setValiditydate(c.getTime());
}
else
{
fund.setNav_entry_date(c.getTime());
mfp.getDc().setValiditydate(c.getTime());
}
RequestContext context2 = RequestContext.getCurrentInstance();
if(sector.equals("open-end")){
context2.execute("openenddialog.show();");
}
else if(sector.equals("close-end")){
context2.execute("closeenddialog.show();");
}
else if(sector.equals("pension")){
context2.execute("pensiondialog.show();");
}
}

Want to compare the date with today's date and update the database.

I am trying to compare the userr entered date with today's date and update the database accordingly. This is how i am doing..
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy");
today = df.format(c.getTime());
//===================================================================
try{
ContentValues val1 = new ContentValues();
val1.put(CPUser.Data.TASK_TYPE, "Todays Task");
getContentResolver().update(CPUser.Data.CONTENT_URI, val1, CPUser.Data.TASK_DUE_DATE + "=" +"'"+today+"'",null);
ContentValues val2 = new ContentValues();
val2.put(CPUser.Data.TASK_TYPE, "Overdue Task");
getContentResolver().update(CPUser.Data.CONTENT_URI, val2, CPUser.Data.TASK_DUE_DATE + "<" +"'"+today+"'",null);
ContentValues val3 = new ContentValues();
val3.put(CPUser.Data.TASK_TYPE, "Active Task");
getContentResolver().update(CPUser.Data.CONTENT_URI, val3, CPUser.Data.TASK_DUE_DATE + ">" +"'"+today+"'",null);
}
Catch(Exception ex)
{ }
If you want to store dates as text in the database, you always have to use "yyyy-MM-dd" format, otherwise you would not be able to do comparisons other than equal ("="). What I do is to save all dates, times and timestamps as INT using Unix Epoch. This allows you to display dates in different formats (using locale for example) to display dates, without first parsing the date. It also allows any type of comparison (equals, greater than etc). The functions are straight forward:
public static long timestampFromUnixEpoch(long unixepoch) {
if (unixepoch == 0)
return 0;
return (unixepoch * 1000) - TimeZone.getDefault().getRawOffset();
}
public static long unixEpochFromTimestamp(long timestampMS) {
if (timestampMS == 0)
return 0;
return ((timestampMS + TimeZone.getDefault().getRawOffset()) / 1000);
}
public static long dateToUnixEpoch(Date date) {
if (date == null)
return 0;
return unixEpochFromTimestamp(date.getTime());
}
public static Date unixEpochToDate(long unixepoch) {
if (unixepoch == 0)
return null;
return new Date(timestampFromUnixEpoch(unixepoch));
}

How do I make DateTextBox (dojo) still display invalid value date after submitting screen?

I'm using DateTextBox from dojo library in my Web page.
After entering an invalid value manually in DateTextbox then submitting the screen, this value disappears :(.
My idea is to keep showing this value so that users can see which wrong value they have entered.
How can I do this?
Any help is highly appreciated,
Thanks in advance :)
thanks for your response and comments. I think what you should do is to make a new pop-up windows to hold message ‘Invalid date’ after clicking your submit button. Just what I did in my example, I makes a class and called ‘AlMessageBox.Show(this, "Invalid Date"). once I edit the date say ‘5/32/2011’ and then submit, there should be a pop-up window 'Invalid Date' then, When I click Ok the date I had entered ‘5/32/2011’ is still there.
See this simple code in c# if ever could help you.
//// In your code-behind:
//// String formate should ‘mm/dd/yyyy’
if (!IsValidDate( dateFrom))
{
AlMessageBox.Show(this, "Invalide Date");
this.txtDateFrom.Focus();
return;
}
Proceed....
.....
// String formate should ‘mm/dd/yyyy’
public static Boolean IsValidDate(string date)
{
bool retValue = true;
if (date == string.Empty)
{
return false;
}
if ((date.Split(‘/’).Length – 1) != 2) // Count the occurence of ‘/’ should be 2
{
return false;
}
int mon = date.Split(‘/’)[0].ToInt();
int day = date.Split(‘/’)[1].ToInt();
int yr = date.Split(‘/’)[2].ToInt();
if (mon > 12 || mon == 0) // Validate month
{
return false;
}
int daysLimitInMonth = GetDaysInMonth(mon);
if (day > daysLimitInMonth || day == 0 )
{
return false;
}
if (yr < 1000 ) // Bellow 1000 years is not invalid
{
return false;
}
return retValue;
}
private static int GetDaysInMonth(int mon)
{
int daysLimitInMonth = 31;
switch (mon)
{
case 2: // case month is Feb
if (IsLeapYear(mon)) // determine the year if is Leap Year
daysLimitInMonth = 29;
else
daysLimitInMonth = 28;
break;
case 4: // April
daysLimitInMonth = 30;
case 6: // June
daysLimitInMonth = 30;
case 9: // Sept
daysLimitInMonth = 30;
case 11: // Nov
daysLimitInMonth = 30;
default:
daysLimitInMonth = 31;
break;
}
return daysLimitInMonth;
}
private static bool IsLeapYear(int year)
{
if ((year % 400) == 0)
return true;
if ((year % 100) == 0)
return false;
if ((year % 4) == 0)
return true;
return false;
}
public class AlMessageBox
{
private static Hashtable m_executingPages = new Hashtable();
private MessageBox() { }
public static void Show(string sMessage)
{
// If this is the first time a page has called this method then
if (!m_executingPages.Contains(HttpContext.Current.Handler))
{
// Attempt to cast HttpHandler as a Page.
Page executingPage = HttpContext.Current.Handler as Page;
if (executingPage != null)
{
// Create a Queue to hold one or more messages.
Queue messageQueue = new Queue();
// Add our message to the Queue
messageQueue.Enqueue(sMessage);
// Add our message queue to the hash table. Use our page reference
// (IHttpHandler) as the key.
m_executingPages.Add(HttpContext.Current.Handler, messageQueue);
// Wire up Unload event so that we can inject
// some JavaScript for the alerts.
executingPage.Unload += new EventHandler(ExecutingPage_Unload);
}
}
else
{
// If were here then the method has allready been
Queue queue = (Queue)m_executingPages[HttpContext.Current.Handler];
// Add our message to the Queue
queue.Enqueue(sMessage);
}
}
public static void Show(System.Web.UI.Page page, string msg)
{
ScriptManager.RegisterClientScriptBlock(page, page.GetType(),
"clientScript", "javascript:alert('" + msg + "');", true);
}
private static void ExecutingPage_Unload(object sender, EventArgs e)
{
// Get our message queue from the hashtable
Queue queue = (Queue)m_executingPages[HttpContext.Current.Handler];
if (queue != null)
{
StringBuilder sb = new StringBuilder();
// How many messages have been registered?
int iMsgCount = queue.Count;
// Use StringBuilder to build up our client slide JavaScript.
sb.Append("<script language='javascript'>");
// Loop round registered messages
string sMsg;
while (iMsgCount-- > 0)
{
sMsg = (string)queue.Dequeue();
sMsg = sMsg.Replace("\n", "\\n");
sMsg = sMsg.Replace("\"", "'");
sb.Append(#"alert( """ + sMsg + #""" );");
}
// Close our JS
sb.Append(#"</script>");
// Were done, so remove our page reference from the hashtable
m_executingPages.Remove(HttpContext.Current.Handler);
// Write the JavaScript to the end of the response stream.
HttpContext.Current.Response.Write(sb.ToString());
}
}
}
Hi Yugi, Sorry to say that I' never try dojo's widget, what am I done on my web page to have an entry of date is
that I use AjaxControlToolkit for filtering valid input character which tageted to my date textbox.
If you want to try this you may download a AjaxControlToolkit
with which should File version: 3.0.20229.0
from google search.
You should reference AjaxControlToolkit.dll file in your solution project.
then register it:
See Client code ViewProcessedClaims.aspx.cs
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ViewProcessedClaims.aspx.cs"
Inherits="MedilinkSites.ViewProcessedClaims" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
Then in the Body tag:
Example:
<tr>
<td>
<asp:TextBox ID="txtDateFrom" runat="server" Width="70px" OnTextChanged="txtDateFrom_TextChanged"></asp:TextBox>
<cc1:CalendarExtender PopupButtonID="ImageDatePicker" ID="CalFrom" TargetControlID="txtDateFrom"
runat="server">
</cc1:CalendarExtender>
<cc1:FilteredTextBoxExtender ID="ftDateFrom" ValidChars="1234567890/" TargetControlID="txtDateFrom"
runat="server">
</cc1:FilteredTextBoxExtender>
<asp:ImageButton ID="ImageDatePicker" runat="server" ImageUrl="images/Calendar.png"
AlternateText="Click here to display calendar" Height="16px" />
</td>
</tr>
In you submit button_click:
string dateFrom = this.txtDateFrom.Text;
if (!IsValidDate( dateFrom)) // Calling my previous function IsValidDate()
{
AlMessageBox.Show(this, "Invalide Date"); // Calling my prev. pop-up message box
this.txtDateFrom.Focus();
return;
}
Note: just include my previous code behind that i'd made ....
Hope this could help...
Regards,