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
Related
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
I have two properties of time stamp without AM/PM. What's needed is to find the total time spent in quarter unit determined by _factor. Then there is a rounddown & roundup concept which is determined by _roundDown value as cut off point. Finally, returning a decimal value back after the calculation.
This resides in a class definition that sets up a property TotalTime. Because of this reason, I would like the code to be efficient. Excuse my code as this is the last piece of the project and want to get it done.
How can I improve the code: I am using mod calculation.
private decimal ComputeTotalTime(int _increment)
{
decimal _TotalHours = 0;
int _roundDown = 7, _factor = 15;
int int_TotalHours = 0;
if (String.IsNullOrEmpty(StartTime) || String.IsNullOrEmpty(EndTime)) return _TotalHours;
DateTime timeFromInput = DateTime.ParseExact(StartTime, "H:m", null);
DateTime timeToInput = DateTime.ParseExact(EndTime, "H:m", null);
//Here found a problem that we need to ensure that EndTime is greater than StartTime
//In one run, StartTime is 10:30 and EndTime is 2:32
//but the DateTime variables took is as 10:30 PM and 2:32 PM hence producing negative difference
TimeSpan ts = timeToInput.Subtract(timeFromInput)
int_TotalHours = ts.Hours * 60 + ts.Minutes;
if (int_TotalHours % _factor == 0) { /*I'm Perfect, no need to round*/ }
else if (int_TotalHours % _factor <= _roundDown) {
//Round down to nearest 15th, quarter
int_TotalHours = int_TotalHours - (int_TotalHours % _factor); }
else { //Round up to nearest quarter
int_TotalHours = int_TotalHours + (_factor - int_TotalHours % _factor); }
_TotalHours = Convert.ToDecimal(int_TotalHours / 60.00);
_TotalHours = (_TotalHours * 100) / 100;
return _TotalHours;
}
Thank you for your help.
I would like to calculate the remaining minutes to the "next" half an hour or hour.
Say i get a start time string of 07:15, i want it to calculate the remaining minutes to the nearest half an hour (07:30).
That would be 15min.
Then i can also have an instance where the start time can be 07:45 and i want it to calculate the remaining minutes to the nearest hour (08:00).
That would also be 15min.
So any string less then 30min in a hour would calculate to the nearest half an hour (..:30) and any string over 30min would calculate to the nearest hour (..:00).
I don't want to do a bunch of if statements, because i get from time strings that can start from and minute in an hour.
This is what i do not want to do:
if (int.Parse(fromTimeString.Right(2)) < 30)
{
//Do Calculation
}
else
{
//Do Calculation
}
public static string Right(this String stringValue, int noOfCharacters)
{
string result = null;
if (stringValue.Length >= noOfCharacters)
{
result = stringValue.Substring(stringValue.Length - noOfCharacters, noOfCharacters);
}
else
{
result = "";
}
return result;
}
Is there not an easier way with linq or with the DateTime class
Use modulo operator % with 30. Your result will be equal to (60 - currentMinutes) % 30. About LINQ its used for collections so i can't realy see how it can be used in your case.
You can use this DateTime tick-round approach to get the timespan until next half hour:
var minutes = 30;
var now = DateTime.Now;
var ticksMin = TimeSpan.FromMinutes(minutes).Ticks;
DateTime rounded = new DateTime(((now.Ticks + (ticksMin/2)) / ticksMin) * ticksMin);
var diff=rounded-now;
var minUntilNext = diff.TotalMinutes > 0 ? diff.TotalMinutes : minutes + diff.TotalMinutes;
var minutesToNextHalfHour = (60 - yourDateTimeVariable.Minutes) % 30;
This should do it:
int remainingMinutes = (current.Minute >= 30)
? 60 - current.Minute
: 30 - current.Minute;
var hhmm = fromTimeString.Split(':');
var mins = int.Parse(hhmm[1]);
var remainingMins = (60 - mins) % 30;
var str = "7:16";
var datetime = DateTime.ParseExact(str, "h:mm", new CultureInfo("en-US"));
var minutesPastHalfHour = datetime.Minute % 30;
var minutesBeforeHalfHour = 30 - minutesPastHalfHour;
I would use modulo + TimeSpan.TryParse:
public static int ComputeTime(string time)
{
TimeSpan ts;
if (TimeSpan.TryParse(time, out ts))
{
return (60 - ts.Minutes) % 30;
}
throw new ArgumentException("Time is not valid", "time");
}
private static void Main(string[] args)
{
string test1 = "7:27";
string test2 = "7:42";
Console.WriteLine(ComputeTime(test1));
Console.WriteLine(ComputeTime(test2));
Console.ReadLine();
}
I have the following Code:
var enteredDate = Convert.ToDateTime("17:45");
var todaysDateTime = DateTime.Now;
var span = enteredDate.Subtract(todaysDateTime);
double totalMins = Math.Ceiling(span.TotalMinutes);
string timeCond;
if (totalMins > 0)
{
if (totalMins < 5)
{
timeCond = Math.Ceiling(span.TotalSeconds) + " seconds left.";
}
else
{
timeCond = totalMins + " minutes left.";
}
}
Given that the time now would be 17:50 the returned second would be a negative figure, I would like to be able to return the seconds or minutes in relation to the code for the next time the time would be 17:45, is this possible?
You could always just add a day:
var span = enteredDate - todaysDateTime;
if (span < TimeSpan.Zero)
{
span += TimeSpan.FromDays(1);
}
(Note that this assumes there are 24 hours between today's 17:45 and tomorrow's 17:45. That isn't true around daylight saving transitions; accommodating for that is feasible, but would make life somewhat more complicated.)
try
var span = Convert.ToDateTime("17:45") > DateTime.Now ? Convert.ToDateTime("17:45") - DateTime.Now : Convert.ToDateTime("17:45").AddDays(1) - DateTime.Now
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();