C# Console application, How to calculate Mobile Bill for any duration? - c#

Lets say We have two billing period for our mobile call, if we call between 0-12, then call rate is 1$/Min & if we call between 12-24, then the rate is 2$/min. A call can starts at any time & lasts for any duration. I need to calculate the bill for the call duration. I'm getting it difficult to work with the datetime type. Also I need a better algorithm to calculate the bill. I'm trying something like this:
DateTime StartTime, EndTime;
decimal Bill = 0;
decimal RemainingDuration;
StartTime = DateTime.Now;
EndTime = DateTime.Now.AddHours(2.5);
var Duration = (EndTime.ToString("H:mm") - StartTime.ToString("H:mm"));
if (StartTime.Hour > 0 && StartTime.Hour < 12)
{
//var RemainingTime = 12.00 - StartTime;
//if (Duration < RemainingTime)
//{
// Bill = (Duration * 60) * 1;
// Console.WriteLine(Bill);
//}
//else
//{
// RemainingDuration = Duration - RemainingTime;
// Bill = ((RemainingTime * 60) * 1) + ((RemainingDuration * 60) * 2);
// Console.WriteLine(Bill);
//}
}
else if (StartTime.Hour > 12 && StartTime.Hour < 24)
{
//var RemainingTime = 24.00 - StartTime.Hour;
//if (Duration < RemainingTime)
//{
// Bill = (Duration * 60) * 2;
// Console.WriteLine(Bill);
//}
//else
//{
// RemainingDuration = Duration - RemainingTime;
// Bill = ((RemainingTime * 60) * 2) + ((RemainingDuration * 60) * 1);
// Console.WriteLine(Bill);
//}
}
Console.ReadLine();
There are some errors for type miss match. the errors are not my prime concern here, I wrote this code assuming the call duration can be maximum 24 hours. I need to write it for unlimited duration. Also Getting hard time to convert types. Code sample would really help. thanks

You're getting a type mismatch since you're converting the DateTime to strings before attempting arithmetic on them. As for the algorithm, well, of course there are thousands of ways you could do it, but here is a simple example that solves your 24 hour problem and perhaps gives you some more ideas.
decimal bill = 0;
DateTime startTime = DateTime.Now;
DateTime endTime = DateTime.Now.AddHours(2.5);
DateTime timeNow = startTime;
while (timeNow <= endTime)
{
decimal rate = (timeNow.Hour >= 12 && timeNow.Hour <= 24) ? 2 : 1;
bill = bill + rate;
Console.WriteLine("{0:HH:mm}, rate: ${1:#,0.00}, bill: ${2:#,0.00}", timeNow, rate, bill);
timeNow = timeNow.AddMinutes(1);
}
Console.WriteLine("Bill: {0:HH:mm} to {1:HH:mm}, {2:#,0} mins, ${3:#,0.00}", startTime, endTime, (endTime - startTime).TotalMinutes, bill);
Console.ReadLine();

Related

How to make 5 minute countdown using TimeOfDay

Candlesticks on stock market charts are created every minute. I have created a count down timer to tell me how many seconds are left until next candlestick is to be created.
//logic for 1 min candlestick
const int MINUTE = 60;
int currentSecond = DateTime.UtcNow.Second;
int nextMin = MINUTE - currentSecond;
minuteLabel.Text = nextMin.ToString();
The chart can also display candlesticks every 5 minutes for a different perspective. So in this scenario a candlestick is created every 5 minutes. This is what I'm having trouble with. How do I create a count down timer to show me how much time is left until the next candlestick is to be created? This is what I have so far:
//inefficient logic for 5 min candlestick
int currentMinute = DateTime.UtcNow.Minute;
int nextFiveMin;
if (currentMinute >= 0 && currentMinute < 5) {
nextFiveMin = ((5 * MINUTE) - (currentMinute * MINUTE)) - currentSecond;
}
else if(currentMinute >= 5 && currentMinute < 10) {
nextFiveMin = ((10 * MINUTE) - (currentMinute * MINUTE)) - currentSecond;
}
else if (currentMinute >= 10 && currentMinute < 15) {
nextFiveMin = ((15 * MINUTE) - (currentMinute * MINUTE)) - currentSecond;
}
//etc all the way to currentMinute > 55
TimeSpan t = TimeSpan.FromSeconds(nextFiveMin);
fiverLabel.Text = t.ToString(#"mm\:ss");
Although this code works fine I think that there's probably a much easier way to implement this that I can't think of.
You can just do this:
int currentMinute = DateTime.UtcNow.Minute;
int diffMinutes = (currentMinute/5 +1) * 5;
int nextFiveMin = ((diffMinutes * MINUTE) - (currentMinute * MINUTE)) - currentSecond;
Another approach:
private void timer1_Tick(object sender, EventArgs e)
{
// from the current time, strip the seconds, then add one minute:
DateTime dt = DateTime.Today.Add(new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, 0)).AddMinutes(1);
// keep adding minutes until it's a multiple of 5
while (dt.Minute % 5 != 0)
{
dt = dt.AddMinutes(1);
}
// display how much time until the next five minute mark:
TimeSpan t = dt.Subtract(DateTime.Now);
fiverLabel.Text = t.ToString(#"mm\:ss");
}

Edit timer number format

I have a code like this:
private IEnumerator RunTimer(float time, int kind_of_function)
{
var seconds = (int) time;
while (time > 0)
{
yield return null;
time -= Time.deltaTime;
if ((int) time != seconds)
{
// Update the text
seconds = (int) time;
timerText.text = string.Format("{0:00}:{1:00}", seconds / 60, seconds % 60);
}
if (seconds == 0)
{
}
}
}
How to change this output format: 0:00 In such a way that if the number of seconds was two-digit then it would look like 00, and if it was one-digit then 0?
As said use one of
#0 where
0 means: I definitely want this digit always
# means: I want this digit only if it is not 0 or is a significant 0
see Custom Numeric Format Strings
D
which basically means: Only show significant decimals digits.
Since you have int you could even also use N which usually includes digits after the comma
see Standard Numeric Format strings
Simply do not define a special format at all.
What you describe is what happens by default anyway if you simply used
string.Format("{0}:{1}", seconds / 60, seconds % 60)
Then I would prefer $ string interpolation which in my opinion is more flexible and better maintainable
timeText.text = $"{seconds / 60}:{seconds % 60}";
or with the formatter
timeText.text = $"{seconds / 60:#0}:{seconds % 60:#0}";
Though in my humble opinion you should stick to what you had. Doesn't it look way better?
Okey apparently what you actually wanted is not displaying the minutes at all if there are only seconds
var minutes = seconds / 60;
if(minutes > 0)
{
timeText.text = $"{minutes}:{seconds % 60:#0}";
}
else
{
timeText.text = $"{seconds:#0}";
}
private IEnumerator RunTimer(float time)
{
var seconds = (int) time;
while (time > 0)
{
yield return null;
time -= Time.deltaTime;
bool moreThanTenSec = time / 10 > 1;
if ((int) time != seconds)
{
// Update the text
seconds = (int) time;
if (moreThanTenSec)
timerText.text = string.Format("{0:00}:{1:00}", seconds / 60, seconds % 60);
else
timerText.text = string.Format("{0:00}:{1:0}", seconds / 60, seconds % 60);
}
if (seconds == 0)
{
}
}

add particular days from given date for one year

I have a start date like "2015-03-10". I want to add 1.25 days per month for the current year from this start date. For example, I have start date "2015-03-10" then for this year the number of days will be 12.50. (1.25 days for each month from March month).
Given date : 2015-11-10 need to add days up to March 31st,2016 : 1.25 * 5 (as from November month, here 5 )(For every month add 1.25 days) Number of days for this year : 6.25
(year start calculated from April and year end considered as March.)
How can i do this in c# can any one help me to do this
Thanks in advance
This example ignores the days of the months, as per your post:
DateTime start;
DateTime end;
// assuming end > start
double value = 1.25 * (end.Month - start.Month + 12 * (end.Year - start.Year) + 1);
EDIT: I can help you to understand this line of code splitting in some steps:
DateTime start = DateTime.Now;
DateTime end = new DateTime(start.Year, 3, 31);
if (start.Month > 3)
end = end.AddYear(1);
double years = end.Year - start.Year;
double months = end.Month - start.Month + 1;
months += (years * 12);
double value = 1.25 * months;
I got it by following :
DateTime endDate = new DateTime(DateTime.Today.Year + 1, 4, 1).AddDays(-1);
if (Convert.ToDateTime(empHiredDate).Month > 4)
{
finMonth = Convert.ToDateTime(empHiredDate).Month - 4;
finMonth = 12 - finMonth;
avail =Convert.ToString(finMonth * 1.25);
}
else if (Convert.ToDateTime(empHiredDate).Month < 3)
{
finMonth = Convert.ToDateTime(empHiredDate).Month + 8;
finMonth = 12 - finMonth;
avail = Convert.ToString(finMonth * 1.25);
}
else if (Convert.ToDateTime(empHiredDate).Month == 4)
{
avail = Convert.ToString(12 * 1.25);
}
else if (Convert.ToDateTime(empHiredDate).Month == 3)
{
avail = Convert.ToString(1 * 1.25);
}

Convert DateTime to Julian Date in C# (ToOADate Safe?)

I need to convert from a standard Gregorian date to a Julian day number.
I've seen nothing documented in C# to do this directly, but I have found many posts (while Googling) suggesting the use of ToOADate.
The documentation on ToOADate does not suggest this as a valid conversion method for Julian dates.
Can anyone clarify if this function will perform conversion accurately, or perhaps a more appropriate method to convert DateTime to a Julian formatted string.
This provides me with the expected number when validated against Wikipedia's Julian Day page
public static long ConvertToJulian(DateTime Date)
{
int Month = Date.Month;
int Day = Date.Day;
int Year = Date.Year;
if (Month < 3)
{
Month = Month + 12;
Year = Year - 1;
}
long JulianDay = Day + (153 * Month - 457) / 5 + 365 * Year + (Year / 4) - (Year / 100) + (Year / 400) + 1721119;
return JulianDay;
}
However, this is without an understanding of the magic numbers being used.
Thanks
References:
DateTime.ToOADate Method
OADate is similar to Julian Dates, but uses a different starting point (December 30, 1899 vs. January 1, 4713 BC), and a different 'new day' point. Julian Dates consider noon to be the beginning of a new day, OADates use the modern definition, midnight.
The Julian Date of midnight, December 30, 1899 is 2415018.5. This method should give you the proper values:
public static double ToJulianDate(this DateTime date)
{
return date.ToOADate() + 2415018.5;
}
As for the algorithm:
if (Month < 3) ...: To make the magic numbers work our right, they're putting February at the 'end' of the year.
(153 * Month - 457) / 5: Wow, that's some serious magic numbers.
Normally, the number of days in each month is 31 28 31 30 31 30 31 31 30 31 30 31, but after that adjustment in the if statement, it becomes 31 30 31 30 31 31 30 31 30 31 31 28. Or, subtract 30 and you end up with 1 0 1 0 1 1 0 1 0 1 1 -2. They're creating that pattern of 1s and 0s by doing that division in integer space.
Re-written to floating point, it would be (int)(30.6 * Month - 91.4). 30.6 is the average number of days per month, excluding February (30.63 repeating, to be exact). 91.4 is almost the number of days in 3 average non-February months. (30.6 * 3 is 91.8).
So, let's remove the 30, and just focus on that 0.6 days. If we multiply it by the number of months, and then truncate to an integer, we'll get a pattern of 0s and 1s.
0.6 * 0 = 0.0 -> 0
0.6 * 1 = 0.6 -> 0 (difference of 0)
0.6 * 2 = 1.2 -> 1 (difference of 1)
0.6 * 3 = 1.8 -> 1 (difference of 0)
0.6 * 4 = 2.4 -> 2 (difference of 1)
0.6 * 5 = 3.0 -> 3 (difference of 1)
0.6 * 6 = 3.6 -> 3 (difference of 0)
0.6 * 7 = 4.2 -> 4 (difference of 1)
0.6 * 8 = 4.8 -> 4 (difference of 0)
See that pattern of differences in the right? That's the same pattern in the list above, the number of days in each month minus 30. The subtraction of 91.8 would compensate for the number of days in the first three months, that were moved to the 'end' of the year, and adjusting it by 0.4 moves the successive differences of 1 (0.6 * 4 and 0.6 * 5 in the above table) to align with the adjacent months that are 31 days.
Since February is now at the 'end' of the year, we don't need to deal with its length. It could be 45 days long (46 on a leap year), and the only thing that would have to change is the constant for the number of days in a year, 365.
Note that this relies on the pattern of 30 and 31 month days. If we had two months in a row that were 30 days, this would not be possible.
365 * Year: Days per year
(Year / 4) - (Year / 100) + (Year / 400): Plus one leap day every 4 years, minus one every 100, plus one every 400.
+ 1721119: This is the Julian Date of March 2nd, 1 BC. Since we moved the 'start' of the calendar from January to March, we use this as our offset, rather than January 1st. Since there is no year zero, 1 BC gets the integer value 0. As for why March 2nd instead of March 1st, I'm guessing that's because that whole month calculation was still a little off at the end. If the original writer had used - 462 instead of - 457 (- 92.4 instead of - 91.4 in floating point math), then the offset would have been to March 1st.
While the method
public static double ToJulianDate(this DateTime date) { return date.ToOADate() + 2415018.5; }
works for modern dates, it has significant shortcomings.
The Julian date is defined for negative dates - i.e, BCE (before common era) dates and is common in astronomical calculations. You cannot construct a DateTime object with the year less than 0, and so the Julian Date cannot be computed for BCE dates using the above method.
The Gregorian calendar reform of 1582 put an 11 day hole in the calendar between October 4th and the 15th. Those dates are not defined in either the Julian calendar or the Gregorian calendar, but DateTime accepts them as arguments. Furthermore, using the above method does not return the correct value for any Julian date. Experiments with using the System.Globalization.JulianCalendar.ToDateTime(), or passing the JulianCalendar era into the DateTime constructor still produce incorrect results for all dates prior to October 5, 1582.
The following routines, adapted from Jean Meeus' "Astronomical Algorithms", returns correct results for all dates starting from noon on January 1st, -4712, time zero on the Julian calendar. They also throw an ArgumentOutOfRangeException if an invalid date is passed.
public class JulianDate
{
public static bool isJulianDate(int year, int month, int day)
{
// All dates prior to 1582 are in the Julian calendar
if (year < 1582)
return true;
// All dates after 1582 are in the Gregorian calendar
else if (year > 1582)
return false;
else
{
// If 1582, check before October 4 (Julian) or after October 15 (Gregorian)
if (month < 10)
return true;
else if (month > 10)
return false;
else
{
if (day < 5)
return true;
else if (day > 14)
return false;
else
// Any date in the range 10/5/1582 to 10/14/1582 is invalid
throw new ArgumentOutOfRangeException(
"This date is not valid as it does not exist in either the Julian or the Gregorian calendars.");
}
}
}
static private double DateToJD(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
// Determine correct calendar based on date
bool JulianCalendar = isJulianDate(year, month, day);
int M = month > 2 ? month : month + 12;
int Y = month > 2 ? year : year - 1;
double D = day + hour/24.0 + minute/1440.0 + (second + millisecond / 1000.0)/86400.0;
int B = JulianCalendar ? 0 : 2 - Y/100 + Y/100/4;
return (int) (365.25*(Y + 4716)) + (int) (30.6001*(M + 1)) + D + B - 1524.5;
}
static public double JD(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
return DateToJD(year, month, day, hour, minute, second, millisecond);
}
static public double JD(DateTime date)
{
return DateToJD(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Millisecond);
}
}
If someone need to convert from Julian date to DateTime , see below :
public static DateTime FromJulianDate(double julianDate)
{
return DateTime.FromOADate(julianDate - 2415018.5);
}
The explanation by David Yaw is spot on, but calculation of the cumulative number of days of the year for the months prior to the given month is anti-intuitive. If you prefer an array of integers to make the algorithm more clear then this will do:
/*
* convert magic numbers created by:
* (153*month - 457)/5)
* into an explicit array of integers
*/
int[] CumulativeDays = new int[]
{
-92 // Month = 0 (Should not be accessed by algorithm)
, -61 // Month = 1 (Should not be accessed by algorithm)
, -31 // Month = 2 (Should not be accessed by algorithm)
, 0 // Month = 3 (March)
, 31 // Month = 4 (April)
, 61 // Month = 5 (May)
, 92 // Month = 6 (June)
, 122 // Month = 7 (July)
, 153 // Month = 8 (August)
, 184 // Month = 9 (September)
, 214 // Month = 10 (October)
, 245 // Month = 11 (November)
, 275 // Month = 12 (December)
, 306 // Month = 13 (January, next year)
, 337 // Month = 14 (February, next year)
};
and the first thre lines of the calculation then become:
int julianDay = day
+ CumulativeDays[month]
+ 365*year
+ (year/4)
The expression
(153*month - 457)/5)
though produces the exact same sequence same integers as the array above for values in the range: 3 to 14; inclusive and does so with no storage requirements. The lack of storage requirements is only virtue in calculating the cumulative number of days in such and obfuscated way.
My code for modified Julian Date uses the same algorithm but a different magic number on the end so that the resulting value matches the Modified Julian Date shown on Wikipedia. I have been using this same algorithm for at least 10 years as the key for daily time series (originally in Java).
public static int IntegerDate(DateTime date)
{
int Month = date.Month;
int Day = date.Day;
int Year = date.Year;
if (Month < 3)
{
Month = Month + 12;
Year = Year - 1;
}
//modified Julian Date
return Day + (153 * Month - 457) / 5 + 365 * Year + (Year / 4) - (Year / 100) + (Year / 400) - 678882;
}
The reverse calculation has more magic numbers for your amusement:
public static DateTime FromDateInteger(int mjd)
{
long a = mjd + 2468570;
long b = (long)((4 * a) / 146097);
a = a - ((long)((146097 * b + 3) / 4));
long c = (long)((4000 * (a + 1) / 1461001));
a = a - (long)((1461 * c) / 4) + 31;
long d = (long)((80 * a) / 2447);
int Day = (int)(a - (long)((2447 * d) / 80));
a = (long)(d / 11);
int Month = (int)(d + 2 - 12 * a);
int Year = (int)(100 * (b - 49) + c + a);
return new DateTime(Year, Month, Day);
}
The below method gives you the julian days starting from 1995/1/1, 00:00:00
/// <summary>
/// "GetJulianDays" will return a Julian Days starting from date 1 Jan 1995
/// </summary>
/// <param name="YYYYMMddHHmmss"></param>
/// <returns>Julian Day for given date</returns>
public string GetJulianDays(DateTime YYYYMMddHHmmss)
{
string DateTimeInJulianFormat = string.Empty;
DateTime julianStartDate = new DateTime(1995, 1, 1, 00, 00, 00); //YYYY,MM,dd,HH,mm,ss
DateTime DateTimeNow = YYYYMMddHHmmss;
double difference = (DateTimeNow - julianStartDate).TotalDays;
int totalDays = int.Parse(difference.ToString());
DateTimeInJulianFormat = string.Format("{0:X}", totalDays);
return DateTimeInJulianFormat;
}
I use some calculations in microcontrollers but require years only between 2000 and 2255.
Here is my code:
typedef struct {
unsigned int8 seconds; // 0 to 59
unsigned int8 minutes; // 0 to 59
unsigned int8 hours; // 0 to 23 (24-hour time)
unsigned int8 day; // 1 to 31
unsigned int8 weekday; // 0 = Sunday, 1 = Monday, etc.
unsigned int8 month; // 1 to 12
unsigned int8 year; // (2)000 to (2)255
unsigned int32 julian; // Julian date
} date_time_t;
// Convert from DD-MM-YY HH:MM:SS to JulianTime
void JulianTime(date_time_t * dt)
{
unsigned int8 m, y;
y = dt->year;
m = dt->month;
if (m > 2) m -= 3;
else {
m += 9;
y --;
}
dt->julian = ((1461 * y) / 4) + ((153 * m + 2) / 5) + dt->day;
dt->weekday = ( dt->julian + 2 ) % 7;
dt->julian = (dt->julian * 24) + (dt->hours );
dt->julian = (dt->julian * 60) + (dt->minutes );
dt->julian = (dt->julian * 60) + (dt->seconds );
}
// Reverse from JulianTime to DD-MM-YY HH:MM:SS
void GregorianTime(date_time_t *dt)
{
unsigned int32 j = dt->julian;
dt->seconds = j % 60;
j /= 60;
dt->minutes = j % 60;
j /= 60;
dt->hours = j % 24;
j /= 24;
dt->weekday = ( j + 2 ) % 7; // Get day of week
dt->year = (4 * j) / 1461;
j = j - ((1461 * dt->year) / 4);
dt->month = (5 * j - 3) / 153;
dt->day = j - (((dt->month * 153) + 3) / 5);
if ( dt->month < 10 )
{
dt->month += 3;
}
else
{
dt->month -= 9;
dt->year ++;
}
}
Hope this helps :D
The wikipedia page you linked contain the code for conversion from either the Julian or the Gregorian calendars. E.g. you can choose to convert a date prior to the Gregorian calendar era, which is called 'the proleptic Gregorian calendar'.
Depending on the chosen 'conversion' calendar the output will vary. This is because the calendars themselves are different constructs and deals with alignments/corrections of various sorts in different ways.
public enum ConversionCalendar
{
GregorianCalendar,
JulianCalendar,
}
public static int ConvertDatePartsToJdn(int year, int month, int day, ConversionCalendar conversionCalendar)
{
switch (conversionCalendar)
{
case ConversionCalendar.GregorianCalendar:
return ((1461 * (year + 4800 + (month - 14) / 12)) / 4 + (367 * (month - 2 - 12 * ((month - 14) / 12))) / 12 - (3 * ((year + 4900 + (month - 14) / 12) / 100)) / 4 + day - 32075);
case ConversionCalendar.JulianCalendar:
return (367 * year - (7 * (year + 5001 + (month - 9) / 7)) / 4 + (275 * month) / 9 + day + 1729777);
default:
throw new System.ArgumentOutOfRangeException(nameof(calendar));
}
}
One can also convert back from JDN to date components:
public static void ConvertJdnToDateParts(int julianDayNumber, ConversionCalendar conversionCalendar, out int year, out int month, out int day)
{
var f = julianDayNumber + 1401;
if (conversionCalendar == ConversionCalendar.GregorianCalendar)
f += (4 * julianDayNumber + 274277) / 146097 * 3 / 4 + -38;
var eq = System.Math.DivRem(4 * f + 3, 1461, out var er);
var hq = System.Math.DivRem(5 * (er / 4) + 2, 153, out var hr);
day = hr / 5 + 1;
month = ((hq + 2) % 12) + 1;
year = eq - 4716 + (14 - month) / 12;
}
These methods were created from the code on wikipedia, so they should work, unless I fumbled something up.
Per definition on 1.1.2000 at 11:58:55,800 UTC (J2000.0)
exactly 2451545 JD (julian days) had passed since the very first day.
const long J2000UtcTicks = 630823247358000000L; // (new DateTime(2000,1,1,11,58,55,800)).Ticks
const double TicksPerDay = 24 * 60 * 60 * 1E7; // 100ns is equal to 1 tick
// to convert any
DateTime dt;
// you need to convert to timezone GMT and calc the ticks ...
double ticks = dt.ToUniversalTime().Ticks - J2000UtcTicks;
return 2451545d + ticks / TicksPerDay;
in razo pages:
code:
ViewData["jul"] = DateTime.Now.ToOADate() + 2415018.5;
view:
#ViewData["jul"]
in view only:
#{Double jday= DateTime.Now.ToOADate() + 2415018.5;}
#jday
The following function converts a date to Julian date that matches that of Tradestation Easylanguage:
public double ToJulianDate(DateTime date) { return date.ToOADate(); }

Pretty Date Text in Flex / Flash / Java / C#

Is there a free library or class for formatting a date in a pretty way such as "5 minutes ago" or "yesterday"?
I'd be satisfied with the same code in another language that I could port to Actionscript (like Java or C#)
would this help? Should be very easy to port to AS3.
/*
* JavaScript Pretty Date
* Copyright (c) 2008 John Resig (jquery.com)
* Licensed under the MIT license.
*/
// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time){
var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
diff = (((new Date()).getTime() - date.getTime()) / 1000),
day_diff = Math.floor(diff / 86400);
if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
return;
return day_diff == 0 && (
diff < 60 && "just now" ||
diff < 120 && "1 minute ago" ||
diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
diff < 7200 && "1 hour ago" ||
diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
day_diff == 1 && "Yesterday" ||
day_diff < 7 && day_diff + " days ago" ||
day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}
// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" )
jQuery.fn.prettyDate = function(){
return this.each(function(){
var date = prettyDate(this.title);
if ( date )
jQuery(this).text( date );
});
};
I'm using this Relative Time code for a Twitter widget I'm working on. It's PHP, but nothing feature-specific so a port should be pretty easy.
I ended up writing my own.
/**
* Takes a Date object and returns a string in the format
* "X UNITS ago" where X is a number and UNITS is a unit of
* time. Also has some other strings like "yesterday".
*
* #author Mims Wright (with thanks to John Resig)
*
* #param date The date to convert to a past string.
* #param now Optional time to compare against. Default will be the present.
*/
public function getTimeElapsedString(date:Date, now:Date = null):String {
const SEC_PER_MINUTE:int = 60;
const SEC_PER_HOUR:int = SEC_PER_MINUTE * 60;
const SEC_PER_DAY:int = SEC_PER_HOUR * 24;
const SEC_PER_WEEK:int = SEC_PER_DAY * 7;
const SEC_PER_MONTH:int = SEC_PER_DAY * 30;
const SEC_PER_YEAR:int = SEC_PER_MONTH * 12;
// if now isn't defined, make it a new Date object (the present)
if (!now) { now = new Date(); }
// don't use secondsElapsed here because the values are
// huge so they use uints and are never negative
if (now.time < date.time) { return "in the future"; }
// get the difference in seconds between the two values.
var secondsElapsed:uint = Math.floor((now.time - date.time) / 1000);
// seconds
if (secondsElapsed < SEC_PER_MINUTE) { return "just now"; }
// minutes
if (secondsElapsed < SEC_PER_HOUR) {
var minutes:int = int(secondsElapsed / SEC_PER_MINUTE);
return formatAgoString(minutes, "minute");
}
// hours
if (secondsElapsed < SEC_PER_DAY) {
var hours:int = int(secondsElapsed / SEC_PER_HOUR);
return formatAgoString(hours, "hour");
}
// days
if (secondsElapsed < SEC_PER_WEEK) {
var days:int = int(secondsElapsed / SEC_PER_DAY);
if (days == 1) { return "yesterday"; }
return formatAgoString(days, "day");
}
// weeks
if (secondsElapsed < SEC_PER_MONTH) {
var weeks:int = int(secondsElapsed / SEC_PER_WEEK);
return formatAgoString(weeks, "week");
}
// months
if (secondsElapsed < SEC_PER_YEAR) {
var months:int = int(secondsElapsed / SEC_PER_MONTH);
return formatAgoString(months, "month");
}
// years
return "more than a year ago";
// Returns a string in the format "count unit(s) ago"
function formatAgoString(count:int, unit:String):String {
return count + " " + unit + (count > 1 ? "s" : "") + " ago";
}
}
Going to try PrettyTime (github) in Java now. Multi-language and customizable.

Categories

Resources