Countdown timer in asp.net - c#

I am using asp.net 3.5 with C#.
I want to create a countdown timer and my requirement is like this:
Countdown end date: June 16 2010
So, till June 16 comes my timer will show the remeaning time.
Please let me know how to achieve it, I google it but i didn't get the excat solution to my problem.
Thanks in advance.

This is something you need to solve with Javascript. The only thing you need to do from the server is set the end date as a Javascript variable. You need Javascript because you only load the page from the server. Afterwards you need to handle the countdown on the client.
Javascript
<script type="text/javascript">
function countdown_clock(clockID, year, month, day, hour, minute) {
countdown(clockID, year, month, day, hour, minute);
}
function countdown(clockID, year, month, day, hour, minute) {
Today = new Date();
Todays_Year = Today.getFullYear();
Todays_Month = Today.getMonth();
//Convert both today's date and the target date into miliseconds.
Todays_Date = (new Date(Todays_Year, Todays_Month, Today.getDate(),
Today.getHours(), Today.getMinutes(), Today.getSeconds())).getTime();
Target_Date = (new Date(year, month - 1, day, hour, minute, 00)).getTime();
//Find their difference, and convert that into seconds.
Time_Left = Math.round((Target_Date - Todays_Date) / 1000);
if (Time_Left < 0)
Time_Left = 0;
days = Math.floor(Time_Left / (60 * 60 * 24));
Time_Left %= (60 * 60 * 24);
hours = Math.floor(Time_Left / (60 * 60));
Time_Left %= (60 * 60);
minutes = Math.floor(Time_Left / 60);
Time_Left %= 60;
seconds = Time_Left;
dps = 's'; hps = 's'; mps = 's'; sps = 's';
//ps is short for plural suffix.
if (days == 1) dps = '';
if (hours == 1) hps = '';
if (minutes == 1) mps = '';
if (seconds == 1) sps = '';
var clock = document.getElementById(clockID);
clock.innerHTML = days + ' day' + dps + ' ';
clock.innerHTML += hours + ' hour' + hps + ' ';
clock.innerHTML += minutes + ' minute' + mps + ' and ';
clock.innerHTML += seconds + ' second' + sps;
//Recursive call, keeps the clock ticking.
setTimeout('countdown("' + clockID + '",' + year + ',' + month + ',' + day + ',' + hour + ',' + minute + ');', 1000);
}
</script>
ASP.NET
protected override void OnPreRender(EventArgs e)
{
DateTime endDate = new DateTime(2010, 6, 1, 0, 0, 0);
string script = string.Format("countdown_clock('clock', {0}, {1}, {2}, {3}, {4});", endDate.Year, endDate.Month, endDate.Day, endDate.Hour, endDate.Minute);
ScriptManager.RegisterStartupScript(this, this.GetType(), "countdown", script, true);
base.OnPreRender(e);
}
Script taken an modified for example purpose from My Little Scripts.

If you like it easy, use DateTime.
DateTime EventTime = new DateTime(2010, 6, 16);
TimeSpan Duration = EventTime - DateTime.Now;
string TimeTillEvent = Duration.ToString();

Related

Return Months & days from TimeSpan asp.net

I want to return in Seconds, Minuites, Hours, Days, Months et Years from Datetime created.
I wrote this snippet of code
public static string ReturnCreatedSince(DateTime createdOn)
{
//Get current datetime
var today = DateTime.Now;
// Get days in current month
var daysInMonth = DateTime.DaysInMonth(today.Year, today.Month);
double seconds = 60;
double minutes = seconds * 60;
double hours = minutes * 60;
double days = hours * 24;
//double weeks = days * 7;
double months = days * daysInMonth;
double years = months * 12;
//Convert created datetime to seconds
var datetimeInSeconds = (today - createdOn).TotalSeconds;
var createdSince = string.Empty;
if (datetimeInSeconds <= seconds) //seconds between 1 to 60
{
return TimeSpan.FromSeconds(datetimeInSeconds).Seconds.ToString() + " sec";
}
else if (datetimeInSeconds <= minutes)// Minuites between 1 to 60
{
return TimeSpan.FromSeconds(datetimeInSeconds).Minutes.ToString() + " mins";
}
else if (datetimeInSeconds <= hours)// Hours between 1 to 24
{
return TimeSpan.FromSeconds(datetimeInSeconds).Hours.ToString() + " hrs";
}
else if (datetimeInSeconds <= days)// Days between 1 to 24
{
return TimeSpan.FromSeconds(datetimeInSeconds).Days.ToString() + " jrs";
}
else if (datetimeInSeconds <= months)// Months between 1 to 24
{
return (datetimeInSeconds / months).ToString() + " m";
}
else if (datetimeInSeconds <= years)// Years between 1 to 12
{
return (datetimeInSeconds / years).ToString() + " yrs";
}
else
{
return createdOn.ToShortDateString();
}
}
I tested the code with the following values
Edited
For a given datetime
if the number of second is less than 60 then it should return the value in second.
if the number of second is less greater 60 and less than (60 * 60) secs then it should return the value in mins , the same apply for hours, days months and years
Now i have this date "createdOn": "2017-10-16T14:41:16.557" and return 41 days instead of 1 month expected.
how can i fix it
#Tarik solution for months will get you the total number of months between the startDate and endDate.
To get the last remaining months, include this while loop statement.
DateTime startDate = new DateTime(2003, 1, 1);
DateTime endDate = new DateTime(2007, 12, 1);
int nbYears = endDate.Year - startDate.Year;
int nbMonths = ((endDate.Year - startDate.Year) * 12) + endDate.Month - startDate.Month;
while (nbMonths > 12)
{
nbMonths = nbMonths % 12;
}
Console.WriteLine($"{nbYears} year(s) and {nbMonths} month(s)");
Without the while loop, it prints: 4 year(s) and 59 month(s)
With the while loop, it prints: 4 year(s) and 11 month(s)
It might be easier to use embedded methods :
DateTime startDate = new DateTime(1970, 01, 01);
DateTime endDate = DateTime.Now.ToUniversalTime();
TimeSpan diff = (endDate - startDate);
Console.WriteLine("Number of seconds:" + diff.TotalSeconds);
Console.WriteLine("Number of minutes:" + diff.TotalDays);
Console.WriteLine("Number of hours:" + diff.TotalHours );
Console.WriteLine("Number of days:" + diff.TotalDays);
//months
int nbMonths = ((endDate.Year - startDate.Year) * 12) + endDate.Month - startDate.Month;
Console.WriteLine("Number of months:" + nbMonths);
//years
int nbYears = endDate.Year - startDate.Year;
Console.WriteLine("Number of years:" + nbYears);
Console.ReadKey();

Milliseconds to the highest possible time value before reaching 0,xx

I would like to write a converter from milliseconds to the highest possible time value before reaching a 0,x value.
Let me clarify this with examples.
Let's assume you have 1500ms this should result in 1,5secs, because its the highest possible digit value not resulting in 0,x.
So different examples would be
10ms = 10,0ms
100ms = 100,0ms
1000ms = 1,0sec
10000ms = 10,0sec
100000ms = 1,6min
1000000ms = 16,0min
10000000ms = 2,7hours
(The method should more or less be endless, so from hours to days, to weeks, to months, to years, to decades and so on...)
Is there a .net method for this?
Something like the following
public static string ConversionMethod(UInt64 ms)
{
// change output format as needed
string format = "######.###";
var cutoffs = new List<UInt64>() {
1000, // second
60000, // minute
3600000, // hour
86400000, // day
604800000, // week = day * 7
2592000000, // month = day * 30
31536000000, // year = day * 365
315360000000, // decade = year * 10
3153600000000, // century = decade * 10 (100 years)
31536000000000, // millenia = century * 10 (1000 years)
31536000000000000 // megayear = year * 100000
// 18446744073709551615 // UInt64 MaxValue
// 31536000000000000000 // gigayear = year * 100000000
};
var postfix = new List<String>() {
"second",
"minute",
"hour",
"day",
"week",
"month",
"year",
"decade",
"century",
"millenia",
"megayear"
};
// The above are listed from smallest to largest for easy reading,
// but the comparisons need to be made from largest to
// smallest (in the loop below)
cutoffs.Reverse();
postfix.Reverse();
int count = 0;
foreach (var cutoff in cutoffs)
{
if (ms > cutoff)
{
return ((decimal)((decimal)ms / (decimal)cutoff)).ToString(format) + " " + postfix[count];
}
count++;
}
return ms + " ms";
}
Conversion for the fraction is a bit dirty, might want to clean that up. Also, you'll have to decide how you want to handle leap years (and leap seconds), etc.
While not the final solution, maybe TimeSpan can help you achieve what you are looking for.
It is to be noted however, TimeSpan supports only up to TotalDays.
var timespan = TimeSpan.FromMilliseconds(1500);
var seconds = timespan.TotalSeconds; // equals: 1.5
It seems the TimeSpan class is the closest thing that meets your need, but clearly it's not exactly what you want. My take on it would look something like this:
public static string ScientificNotationTimespan(int milliseconds)
{
var timeSpan = new TimeSpan(0, 0, 0, 0, milliseconds);
var totalDays = timeSpan.TotalDays;
if (totalDays < 7)
{
if (timeSpan.TotalDays > 1) return timeSpan.TotalDays.ToString() + " days";
if (timeSpan.TotalHours > 1) return timeSpan.TotalHours.ToString() + " hours";
if (timeSpan.TotalMinutes > 1) return timeSpan.TotalMinutes.ToString() + " minutes";
if (timeSpan.TotalSeconds > 1) return timeSpan.TotalSeconds.ToString() + " seconds";
return milliseconds.ToString() + "milliseconds";
}
var weeks = totalDays / 7;
//How long is a month? 28, 29, 30 or 31 days?
var years = totalDays / 365;
if (years < 1) return weeks.ToString() + " weeks";
var decades = years / 10;
if (decades < 1) return years.ToString() + " years";
var centuries = decades / 10;
if (centuries < 1) return decades.ToString() + " decades";
var millenia = centuries / 10;
if (millenia < 1) return centuries.ToString() + " centuries";
return millenia.ToString() + " millenia";
}
Here is solution for years, months using DateTime and Gregorian calendar (meaning leap years, calendar months). Then it uses the TimeSpan solution as already submitted.
static string ToMostNonZeroTime(long ms) {
const int hundretsNanosecondsInMillisecond = 10000;
long ticks = (long)ms * hundretsNanosecondsInMillisecond;
var dt = new DateTime(ticks);
if((dt.Year - 1) > 0) { // starts with 1
double daysToYear = (dt.DayOfYear - 1) * 1.0 / (DateTime.IsLeapYear(dt.Year) ? 366 : 365);
daysToYear += dt.Year - 1;
return $"{daysToYear:0.0} years";
}
if((dt.Month - 1) > 0) {
double daysToMonth = (dt.Day - 1) * 1.0 / DateTime.DaysInMonth(dt.Year, dt.Month);
daysToMonth += dt.Day - 1;
return $"{daysToMonth:0.0} months";
}
// can use TimeSpan then:
var ts = TimeSpan.FromMilliseconds(ms);
if(ts.TotalDays >= 1)
return $"{ts.TotalDays:0.0} days";
if(ts.TotalHours >= 1)
return $"{ts.TotalHours:0.0} hours";
if(ts.TotalMinutes >= 1)
return $"{ts.TotalMinutes:0.0} minutes";
if(ts.TotalSeconds >= 1)
return $"{ts.TotalSeconds:0.0} seconds";
return $"{ms} milliseconds";
}
It prints
100ms: 100 milliseconds
1000ms: 1.0 seconds
10000ms: 10.0 seconds
100000ms: 1.7 minutes
1000000ms: 16.7 minutes
10000000ms: 2.8 hours
100000000ms: 1.2 days
1000000000ms: 11.6 days
20000000000ms: 19.6 months
200000000000ms: 6.3 years
Have a look at https://ideone.com/QZHOM4

Julian Date to DateTime INCLUDING HOURS AND MINUTE

I'm trying to convert a Julian Date which includes hours minutes and seconds to a DateTime in C#.
This is the number: 2457285.7795969
I can calculate the DateTime excluding the hours and the minutes with this function.
public static DateTime FromJulian(long julianDate)
{
long L = julianDate + 68569;
long N = (long)((4 * L) / 146097);
L = L - ((long)((146097 * N + 3) / 4));
long I = (long)((4000 * (L + 1) / 1461001));
L = L - (long)((1461 * I) / 4) + 31;
long J = (long)((80 * L) / 2447);
int Day = (int)(L - (long)((2447 * J) / 80));
L = (long)(J / 11);
int Month = (int)(J + 2 - 12 * L);
int Year = (int)(100 * (N - 49) + I + L);
return new DateTime(Year, Month, Day);
}
It should be as simple as:
public static DateTime FromJulian(double julianDate)
{
return new DateTime(
(long)((julianDate - 1721425.5) * TimeSpan.TicksPerDay),
DateTimeKind.Utc);
}
As you can see, 1721425.5 is the so-called Gregorian epoch, i.e. the value the Julian date had at the beginning of the proleptic Gregorian calendar, at 0001 January 1, 00:00:00.0000000, where the .NET DateTime has its origin.
EDIT: If you want to make sure your method throws an exception on "extreme" inputs instead of returning an invalid value, do this:
public static DateTime FromJulian(double julianDate)
{
return new DateTime(
checked((long)((julianDate - 1721425.5) * TimeSpan.TicksPerDay)),
DateTimeKind.Utc);
}
Note that we do the multiplication with the double operator *(double, double) overload (built-in in C#). This gives an error as little as possible. The conversion from double to long will throw in checked context if the double is outside the range of long. If that conversion goes well, the DateTime constructor may throw if the value of the long is out of range for a .NET DateTime.
NEW EDIT: Inspired by another thread (Convert DateTime to Julian Date in C# (ToOADate Safe?)) you can also work out a very simple solution using DateTime.FromOADate. However, see another Stack Overflow post by myself on precision short-comings of the FromOADate method.
Is this what you are looking for: Convert Julian Date with Time (H/m/s) to Date Time in C#?
Applying that answer, converting your value of 2457285.7795969 results in 9/19/2015 11:42:37 PM.
Before Ladi answered with what I was looking for....
double L = DateTime.Now.ToOADate() + 2415018.5 + 68569;
double HMS = L-(int)L-0.5;
int Hours = (int)(24*HMS);
HMS=HMS - (double)(Hours/24.0);
int Mins = (int)(24*60*HMS);
HMS=HMS - (double)(Mins/(24.0*60));
int Secs = (int)(24*60*60*HMS);
long N = (long)((4 * L) / 146097);
L = L - ((long)((146097 * N + 3) / 4));
long I = (long)((4000 * (L + 1) / 1461001));
L = L - (long)((1461 * I) / 4) + 31;
long J = (long)((80 * L) / 2447);
int Day = (int)(L - (long)((2447 * J) / 80));
L = (long)(J / 11);
int Month = (int)(J + 2 - 12 * L);
int Year = (int)(100 * (N - 49) + I + L);
DateTime test = new DateTime(Year, Month, Day);
Console.WriteLine("Hours-"+Hours);
Console.WriteLine("Mins-" + Mins);
Console.WriteLine("Secs-"+ Secs);
Console.WriteLine(test);
Console.WriteLine(DateTime.Now.ToString());

How to write a method to get a value in seconds and print in Hours, Minutes and Seconds

Ok, so this was my first question on StackOverflow, I see the comments haven't been great (and the post keeps getting deleted before I have had a chance to fix it). Give me a chance! My understanding was the question should be as direct as possible and not create 'discussions'?
This is what I have tried already, but the output is not what I expect
int secondsToHours(seconds) {
int totalSec = seconds;
int hrs = totalSec % 3600;
int secs = totalSec % 60;
int mins = totalSec / 60;
string result = hrs + ":" + mins + ":" + secs;
Console.WriteLine(result);
Console.ReadLine();
}
You can use TimeSpan struct:
TimeSpan ts = TimeSpan.FromSeconds(seconds);
And then build string you want:
ts.ToString(#"hh\:mm\:ss")
Look at the TimeSpan class
TimeSpan span = TimeSpan.FromSeconds(total seconds here);
Then look at the Days, Hours, Minutes and Seconds properties, or the TotalDays, TotalHours etc
Well, you could use a TimeSpan object
int seconds = 104700;
TimeSpan ts = new TimeSpan(0, 0, seconds);
Console.WriteLine("Days:" + ts.Days +
", Hours:" + ts.Hours +
", Minutes:" + ts.Minutes +
", Seconds:" + ts.Seconds );
You need to subtract from totalSec. For 4700 as example;
int left;
int hrs = totalSec / 3600; // hrs will be 1
left = totalSec - hrs * 3600; //left will be 1100
int mins = left / 60; //mins will be 18
left = left - mins * 60; // left will be 20
int secs = left; // secs will be 20
As a solution, 4700 will be 1 hours, 18 minutes and 20 seconds.
But using TimeSpan properties would be better such a case. You can use TimeSpan(Int32, Int32, Int32) constructor like;
TimeSpan ts = new TimeSpan(0, 0, seconds);
int hrs = ts.Hours; // 1
int mins = ts.Minutes; // 18
int secs = ts.Seconds; // 20
Simplest way would be using TimeSpan as already suggested in previous answer but also you could try this if you want to do it using Math:
private static void secondsToHours(int seconds)
{
int hrs = seconds / 3600;
int remainder = seconds % 3600;
int mins = remainder / 60;
int secs = seconds % 60;
string result = hrs + ":" + mins + ":" + secs;
Console.WriteLine(result);
Console.ReadLine();
}

Datetime according to Client location

I have The Date time in UTC in database, now I want to show that time according to the User's Timezone or user's computer machine, like if user A has summit a question from India then User A can see the Submitted date according to India, if user A goes to USA then it shows according to USA, and if User B is in China then He can view that question according to China.
how can I do that via C# or javascript.
any one can help me to do that.
You will need to use JavaScript to gather the necessary information from the browser - for this part see http://www.pageloom.com/automatic-timezone-detection-with-javascript
When you have this information you can setup a TimeZone / TimeZoneInfo which in turn can be used to adjust your UTC DateTime values.
Another easier option is using a jQuery plugin called TimeAgo.
For details see C# UTC to Users Local Time
you can do like this.. by using javascript.....
This code will give you client time zone offset in standard format....
<script type="text/javascript">
// Original script by Josh Fraser (http://www.onlineaspect.com)
// Some customization applied in this script code
var minutes;
function calculate_time_zone() {
var rightNow = new Date();
var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0); // jan 1st
var june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
var temp = jan1.toGMTString();
var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ") - 1));
temp = june1.toGMTString();
var june2 = new Date(temp.substring(0, temp.lastIndexOf(" ") - 1));
var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
var dst;
if (std_time_offset == daylight_time_offset) {
dst = "0"; // daylight savings time is NOT observed
} else {
// positive is southern, negative is northern hemisphere
var hemisphere = std_time_offset - daylight_time_offset;
if (hemisphere >= 0)
std_time_offset = daylight_time_offset;
dst = "1"; // daylight savings time is observed
}
var i;
// Here set the value of hidden field to the ClientTimeZone.
minutes = convert(std_time_offset);
TimeField = document.getElementById("HiddenFieldClientTime");
TimeField.value = minutes;
alert('your time zone is ' + minutes);
}
// This function is to convert the timezoneoffset to Standard format
function convert(value) {
var hours = parseInt(value);
value -= parseInt(value);
value *= 60;
var mins = parseInt(value);
value -= parseInt(value);
value *= 60;
var secs = parseInt(value);
var display_hours = hours;
// handle GMT case (00:00)
if (hours == 0) {
display_hours = "00";
} else if (hours > 0) {
// add a plus sign and perhaps an extra 0
display_hours = (hours < 10) ? "+0" + hours : "+" + hours;
} else {
// add an extra 0 if needed
display_hours = (hours > -10) ? "-0" + Math.abs(hours) : hours;
}
mins = (mins < 10) ? "0" + mins : mins;
return display_hours + ":" + mins;
}
// Adding the function to onload event of document object
onload = calculate_time_zone;
</script>
I recommended you pls go through this link
and take a look at this one also time detection

Categories