How to check current time is 12 noon in c#? - asp.net

i need to check current time is 12 noon using c# and timer tick event is used to execute the code
int secs = System.DateTime.Now.Second;
int hours = System.DateTime.Now.Hour;
int minutes = System.DateTime.Now.Minute;
string AmPm = DateTime.Now.ToString("tt");
if (Convert.ToInt32("12") == hours && Convert.ToInt32("0") == minutes && Convert.ToInt32("0") == secs && AmPm.ToUpper().Trim() == "PM")
{
}
else
{}

You should just be able to do:
var is_noon = (
DateTime.Now.Hour == 12 &&
DateTime.Now.Minute == 0 &&
DateTime.Now.Second == 0
);
No need to convert strings to ints, you're using literal values anyhow.
However as Hans Kesting pointed out, depending on the Timer you're using there is a chance for inaccuracy so you'd want some leniency, personally, I'd drop checking for seconds.

Related

calculating time differences using moment.js

Friends,
I have an array containing checkins and checkouts times and need to calculate the spent time between these operations. For that I iterate through this table partitioning checkins from checkouts in two separated arrays, like that:
var checkins = [];
var checkouts = [];
var results = [];
var index;
for (index = 0; index < $scope.data.registries.length; ++index){
if ($scope.data.registries[index].rType == 0) {
checkins.push(moment($scope.data.registries[index].savedHour, "HH:mm:ss"));
}
else {
checkouts.push(moment($scope.data.registries[index].savedHour, "HH:mm:ss"));
}
}
After that I just iterate over checkins array, calculating the diffs and pushing it into the results array, like this:
for (index = 0; index < checkins.length; ++index){
if (index <= checkouts.length) {
results.push(moment.utc(checkouts[index]).diff(moment(checkins[index])));
}
}
So, now I have an array containing only the diff times, for each pair of checkin checkout. Now I just
make a sum of theses diffs... like this:
var total = null;
for (index = 0; index < results.length; ++index) {
if (index == 0){
total = moment(results[index]);
}
else{
total.add(results[index]);
}
}
if (results.length == 0) {
return "00 hour(s) and 00 minute(s)";
}
else {
return moment.utc(total).format("HH [ hour(s) and ] mm [ minute(s)]");
}
I'm not getting the correct amount of time.... for the following sample data:
checkin 07:32
checkout 07:34 ->
difference: 2 minutes
checkin 08:20
checkout 08:53 ->
difference: 33 minutes
I should have a total of 35 minutes, but
its always changing according to current time... for example, here now is 10:51 (am)
and this function is returning 2h and 37m
I dont see what is wrong... could someone point it out?
A few things:
You're subtracting UTC against local time:
moment.utc(checkouts[index]).diff(moment(checkins[index]))
^^^^^^^^^^ ^^^^^^
Either both values should be UTC, or both values should be local.
You said your inputs were time-only values. Keep in mind that when you don't specify a date, the current date is assumed. If you are working with local times on a day that has a daylight saving time transition, you may get results that are adjusted by up to an hour. If you intend to work with the current day and want accurate elapsed times, then this should be expected. Otherwise, you'll want to fix the time to a particular date.
You aren't considering time ranges that cross midnight, for example 22:00 to 02:00 should be 4 hours (on most days). You should check if the values are in sequence, and add a day to the checkout value if not.
I did a short example in my Chrome console and got the correct answer with the following:
var start = moment('07:32', "HH:mm:ss")
var stop = moment('07:34', "HH:mm:ss")
var diff1 = moment.utc(stop).diff(moment(start))
start = moment("08:03", "HH:mm:ss")
stop = moment("08:33", "HH:mm:ss")
var diff2 = moment.utc(stop).diff(moment(start))
var total = moment(diff1)
total.add(diff2)
moment.utc(total).format("HH [ hour(s) and ] mm [ minute(s)]");
"00 hour(s) and 32 minute(s)"
So looks like your logic is correct without the arrays and for loops.
Friends... logic problems in my loops hehehheh
I was using
for (index = 0; index < checkins.length; ++index){
if (index <= checkouts.length) {
results.push(moment.utc(checkouts[index]).diff(moment(checkins[index])));
}
}
the correct is
for (index = 0; index < checkins.length; ++index){
if (index <= checkouts.length-1) {
results.push(moment.utc(checkouts[index]).diff(moment(checkins[index])));
}
}

R: data.frame too slow in loops?

I'm backtesting trading strategies with R. This is at the moment my code.
- MergedSet$FXCloseRate contains the closing price for a certain currency pair
- MergedSet$RiskMA is the moving average of a certain risk index
- the rest should be clear
This formula at the Moment is not really fast over 11'000 entries. Why? Are data frames too slow? Where can I optimise here?
############
# STRATEGY #
############
#Null out trades and position
MergedSet$Trade <- 0
MergedSet$Position<-0
MergedSet$DailyReturn<-0
MergedSet$CumulativeReturn<-0
MergedSet$Investment<-0
MergedSet$CumulativeReturn[1:MAPeriod] <- 1
MergedSet$Investment[1:MAPeriod] <- InitialInvestment
#Strategy
n<-nrow(MergedSet)
for(i in seq(MAPeriod+1,n)){
#Updating the position
if(MergedSet$RiskMA[i] <= ParamDwn && MergedSet$RiskMA[i-1] > ParamDwn){
#sell signal, so short if no or long position active otherwise do nothing
if(MergedSet$Position[i-1] == 0 || MergedSet$Position[i-1] == 1){
MergedSet$Position[i] = -1
MergedSet$Trade[i] = 1
}
} else if(MergedSet$RiskMA[i] >= ParamUp && MergedSet$RiskMA[i-1] < ParamUp){
#buy signal, go long if no or short position active, otherwise do nothing
if(MergedSet$Position[i-1] == 0 || MergedSet$Position[i-1] == -1){
MergedSet$Position[i] = 1
MergedSet$Trade[i] = 1
}
} else {
MergedSet$Position[i] = MergedSet$Position[i-1]
}
#Return calculation
if(MergedSet$Position[i] == 1){
#long
MergedSet$DailyReturn[i] = MergedSet$FXCloseRate[i]/MergedSet$FXCloseRate[i-1]-1
} else if(MergedSet$Position[i] == -1){
#short
MergedSet$DailyReturn[i] = MergedSet$FXCloseRate[i-1]/MergedSet$FXCloseRate[i]-1
}
}

Can this date time function be written more efficiently?

The following function returns the difference between two date time values in words (as a string). Can it be written more efficiently/elegantly?
/**
* #hint Returns the difference between two time strings in words.
*/
public string function timeAgoInWords(required date fromTime, date toTime=now())
{
local.secondDiff = dateDiff("s", arguments.fromTime, arguments.toTime);
if (local.secondDiff <= 60)
return "#local.secondDiff# seconds ago";
local.minuteDiff = dateDiff("n", arguments.fromTime, arguments.toTime);
if (local.minuteDiff <= 60)
if (local.minuteDiff < 2)
return "1 minute ago";
else return "#local.minuteDiff# minutes ago";
if (local.minuteDiff <= 1440)
if (local.minuteDiff <= 120)
return "1 hour ago";
else return "#int(local.minuteDiff/60)# hours ago";
if (local.minuteDiff <= 2880)
return "yesterday";
if (local.minuteDiff <= 4320)
return "2 days ago";
local.monthDiff = dateDiff("m", arguments.fromTime, arguments.toTime);
if (local.monthDiff <= 12)
return "#dateFormat(arguments.fromTime, "mmm dd")# at #timeFormat(arguments.fromTime, "h:mm")#";
return "#dateFormat(arguments.fromTime, "mmm dd 'yy")# at #timeFormat(arguments.fromTime, "h:mm")#";
}
This is what I wrote a few months ago, based on the UDF Al Everett posted above in the comment and written in CF9 script style. It won't be more efficient. In fact, it should be slower then your implementation 'cause it has multiple calls to dateDiff(), and needs to set up 2 arrays up front, but the overall line count is shorter and easily understandable.
string function ago(required Date dateThen)
{
var dateparts = ["yyyy","m","d","h","n"];
var datepartNames = ["year","month","day","hour","minute"];
var rightNow = Now();
for (var i = 1; i <= 5; i++) // 5 == arrayLen(dateparts)
{
var diff = dateDiff(variables.dateparts[i], dateThen, rightNow);
if (diff > 1)
return "#diff# #datepartNames[i]#s ago";
if (diff == 1)
return "#diff# #datepartNames[i]# ago";
}
return "Just Now";
}
It looks good to me. You could instead use your first diff (local.secondDiff) for all your tests rather than re-diffing, but this is probably easier to read.

Calculate date from a number

I need a method which would give me the number of hours and minutes from any random number.For example if the random number is 500 i would like to have information as 5 hrs and 0 minutes.Another example is 2359 is 23 hrs 59 minutes.The random number is entered by the user and i am only concerned with the hours and minutes(not seconds).I need not even worry about rounding off of minutes .So i wrote this method ,which to me is not efficient.Can any one suggest a better way of doing it ?or is this good enough?
private void calculateDateTime(int someNumber){
if(someNumber<=0){
return;
}
String number = Integer.toString(someNumber);
String hrs ="";
String mins ="00";
if(number.length()>4){
hrs =number.substring(0, 2);
mins = number.substring(2,4);
}
else{
float f =((float)someNumber)/100;
String s = Float.toString(f);
String [] splitArray = s.split("\\.");
if(splitArray.length>1) {
hrs = splitArray[0];
mins = splitArray[1];
}
}
int hr = Integer.valueOf(hrs);
int min = Integer.valueOf(mins);
if(hr>=24||min>=60){
return;
}
Thats how i am getting the hr and mins respectively.Suggest me a better approach if you have one.
Thanks
Pad the input string with zeros until length is 4 and then spilt the string in the middle?
Maybe:
int hours = someNumber / 100;
int minutes = someNumber % 100;
if(hours >= 24 || minutes >= 60) {
//Do whatever
}
If you want your values to be repeatable, I would use the passed in value as the seed into a Random generator.
Random r = new Random(someNumber);
int hr = r.nextInt(24);
int min = r.nextInt(60);

How do I get browser timezone using Flex/AS3?

How do I get client browser's timezone in Flex/AS3?
Have a look on the following: http://thanksmister.com/2011/10/06/determining-local-timezone-in-actionscript-air-flex-as3/
It may help.
Can you use the timeZoneOffest of the Date object?
Honestly, I believe this just passes back information based on the user's OS settings. I wouldn't have expected a bBrowser to actually have a time zone.
I've been wanting the same thing, but I found nothing on the Internet. I was already using FlexDateUtils (blog post), but it only formats timezones as 'GMT -600'. Luckily, I can safely say that the users of my app will be in the United States, so I modified to 'DateUtils.buildTimeZoneDesignation(date:Date)' as follows. I hope this helps.
private static function buildTimeZoneDesignation( date:Date ):String {
if ( !date ) {
return "";
}
var timezoneOffsetHours:Number = date.getTimezoneOffset() / 60;
// custom timezone handlers (assumes major U.S. zones with daylight savings time dates as of 2011)
if (3 < timezoneOffsetHours && timezoneOffsetHours < 12)
{
var usDST:Boolean = false;
// the date of the Sunday before today unless today is Sunday
var sundayBeforeToday:Number = date.date - date.day;
if (2007 <= date.fullYear) {
// test for since-2007 extended daylight savings time
if (2 < date.month && date.month < 10) {
// daylight savings time (April through October)
usDST = true;
}
else if (date.month == 2) {
// DST starts second Sunday in March
usDST = (7 < sundayBeforeToday);
}
else if (date.month == 10) {
// DST ends first Sunday in November
usDST = (0 < sundayBeforeToday);
}
}
else {
// test for pre-2007 daylight savings time
if (3 < date.month && date.month < 9) {
// daylight savings time (May through September)
usDST = true;
}
else if (date.month == 3) {
// DST starts first Sunday in April
usDST = (0 < sundayBeforeToday);
}
else if (date.month == 9) {
// DST ends last Sunday in October
usDST = (sundayBeforeToday + 7 <= 31);
}
}
// return custom timezone strings for US timezones
switch (timezoneOffsetHours) {
case 4:
// Eastern or Atlantic
return usDST ? "EDT" : "AST";
case 5:
// Central or Eastern
return usDST ? "CDT" : "EST";
case 6:
// Mountain or Central
return usDST ? "MDT" : "CST";
case 7:
// Pacific or Mountain
return usDST ? "PDT" : "MST";
case 8:
// Alaska or Pacific
return usDST ? "AKDT" : "PST";
case 9:
// Hawaii or Alaska
return usDST ? "HADT" : "AKST";
case 10:
// Samoa or Hawaii
return usDST ? "SDT" : "HAST";
case 11:
if (!usDST)
// Samoa
return "SST";
break;
}
}
// else just generate a GMT string
var timeZoneAsString:String = "GMT ";
// timezoneoffset is the number that needs to be added to the local time to get to GMT, so
// a positive number would actually be GMT -X hours
if ( 0 < timezoneOffsetHours && timezoneOffsetHours < 10 ) {
timeZoneAsString += "-0" + ( timezoneOffsetHours ).toString();
} else if ( date.getTimezoneOffset() < 0 && timezoneOffsetHours > -10 ) {
timeZoneAsString += "0" + ( -1 * timezoneOffsetHours ).toString();
}
// add zeros to match standard format
timeZoneAsString += "00";
return timeZoneAsString;
}

Resources