In the attached image , the total voice minutes for July is 30 minutes. However if I pull the call logs for the same month July 2014 (using the instruction in https://www.twilio.com/docs/api/rest/call)
, I get total duration as 17 minutes. Shouldn't the value of usage and total call duration in Log be equal ?.
Here is my test source code for finding the call log files for month July 2014. Any help is greatly appreciated.
public static void callLogs(string AccountSid, string AuthToken)
{
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var request = new CallListRequest();
request.StartTimeComparison = ComparisonType.GreaterThanOrEqualTo;
request.StartTime = new DateTime(2014, 07, 01);
request.EndTimeComparison = ComparisonType.LessThanOrEqualTo;
request.EndTime = new DateTime(2014, 07, 31);
var calls = twilio.ListCalls(request);
int? voiceMinutes = 0;
decimal? totalCost = 0;
foreach (var call in calls.Calls)
{
if ( call.Price != null)
{
voiceMinutes += call.Duration;
totalCost += call.Price ;
}
Console.WriteLine(call.Price +"-" + call.DateCreated + "-" + call.From + "-" + call.To + "-" + call.Status + "-" + call.Duration );
}
Console.WriteLine("Total Voice:" + int.Parse ((voiceMinutes/60).ToString() ));
Console.WriteLine("Total Cost :" + totalCost);
}
For billing minutes, Twilio will round all calls up to the nearest minute. So you should do the same. Something like this:
voiceMinutes += (call.Duration + 60)/ 60;
And then:
Console.WriteLine("Total Voice:" + int.Parse ((voiceMinutes).ToString() ));
I used to work at West Corporation. One of my duties was to manage the billing data for our clients. At West, the contracts were setup so that instead of exact to the second or minute, the billing was done in blocks.
So, for phone calls, for example, you would get charged for a minimum of 15 seconds and then 10 seconds after that.
Twilio might be using a similar billing model.
Related
I have to do the sum of more time spans in a DataTable to use the code below, but the total sum is wrong, what is due to this:
DataTable(dt) values:
09:21
08:28
08:46
04:23
Total hours: 30,97 //97 minutes is not correct
C# Code:
TimeSpan totaleOreMarcaTempo = TimeSpan.Zero;
int conta = 0;
foreach (DataRow dr in dt.Rows)
{
String OreMarcaTempo = tm.ConteggioOreGiornaliere(dr["Data"].ToString()); //This string contains at each cycle 09:21 08:28 08:46 04:23
TimeSpan oreMarcatempo = TimeSpan.Parse(OreMarcaTempo.ToString());
totaleOreMarcaTempo = totaleOreMarcaTempo + oreMarcatempo;
conta++;
}
labelTotaleOreMarcaTempoMod.Text = "" + (int)totaleOreMarcaTempo.TotalHours + ":" + totaleOreMarcaTempo.Minutes.ToString(); //30:58
30.97 is the correct number of hours. It does not mean "30 hours and 97 minutes".
30.97 hours is 30 hours and 58 minutes. 58 / 60 is roughly 0.97.
I think you just need to format your string properly. One way to format it is:
#"{(int)yourTimeSpan.TotalHours}:{yourTimeSpan.Minutes}"
Value 30.97 is correct (30.97 hours, where 0.97 is hour (60 minutes * 0.97 = 58 minutes),
you just need convert fraction of TotalHours to minutes.
var raw = "09:21 08:28 08:46 04:23";
var totalTimespan =
raw.Split(" ")
.Select(TimeSpan.Parse)
.Aggregate(TimeSpan.Zero, (total, span) => total += span);
// Use integer value of TotalHours
var hours = (int)totalTimespan.TotalHours;
// Use actual minutes
var minutes = totalTimespan.Minutes
var output = $"{hours}:{minutes}";
var expected = "30:58";
output.Should().Be(expected); // Pass Ok
You have to change the Format. 0,98 hours = 58,2 minutes
labelTotaleOreMarcaTempoMod.Text =string.Format ("{0:00}:{1:00}:{2:00}",
(int)totaleOreMarcaTempo.TotalHours,
totaleOreMarcaTempo.Minutes,
totaleOreMarcaTempo.Seconds);
To print out a TimeSpan "correctly", just use the correct formatting:
labelTotaleOreMarcaTempoMod.Text = totaleOreMarcaTempo.ToString("c");
or
labelTotaleOreMarcaTempoMod.Text = totaleOreMarcaTempo.ToString("hh':'mm");
EDIT Do note (thanks, Basin) that the second form ignores days.
Reference: Standard TimeSpan Format Strings and Custom TimeSpan Format Strings
30.97 is the correct value but not HH:mm format.
For me the correct solution is :
var total = Math.Floor( totaleOreMarcaTempo.TotalMinutes / 60).ToString() + ":" + Math.Floor( totaleOreMarcaTempo.TotalMinutes % 60).ToString();
I have been trying to make a simple second to hour and minute converter just to practice some C#. The weird thing is as I pass 599 seconds mark, the program subtracts 60 seconds. So, 540 seconds equals 9 minutes; 599 seconds equals 9 minutes 59 seconds, but 600 seconds equals to 9 minutes. I tried using a button to trigger the commands instead of textchanged and button did the job fine. So, I reckon, the root of the problem must be textchanged event itself. I'll be adding three examples. Screenshot images are in Turkish but you will easily get the idea.
How can I solve this, and what causes this problem? This is really mind boggling.
Screenshot
int second, minute, hour, minuteLeft, secondLeft;
private void txtTime_TextChanged(object sender, EventArgs e)
{
CalculateTime();
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
void CalculateTime()
{
if (txtTime.Text != "")
{
second = Convert.ToInt32(txtSure.Text);
secondLeft = second % 60;
second = second - minuteLeft;
minute = second / 60;
minuteLeft = minute % 60;
minute = minute - minuteLeft;
hour = minute / 60;
lblMsg.Text = hour.ToString() + " hours, " + minuteLeft.ToString() + " minutes " + secondLeft.ToString() + " seconds.";
}
else
{
lblMsg.Text = "";
}
You are subtracting minuteLeft from the number of seconds:
second = second - minuteLeft;
That should be subtracting the secondLeft value:
second = second - secondLeft;
You could consider attacking the problem in a different way:
var durationInSeconds = Convert.ToInt32(txtTime.Text);
var duration = new TimeSpan(0, 0, durationInSeconds);
var second = duration.Seconds;
var minute = duration.Minutes;
var hour = Convert.ToInt32(Math.Truncate(duration.TotalHours));
TimeSpan is well suited to this class of problem, and will allow you to 'automatically' extract the hour, minute and second component of the duration.
You could also consider replacing:
hour.ToString() + " hours, " + minuteLeft.ToString() + " minutes " + secondLeft.ToString() + " seconds.";
with a call to:
public static string ToPrettyFormat(TimeSpan timeSpan)
{
var dayParts = new[] { GetDays(timeSpan), GetHours(timeSpan), GetMinutes(timeSpan) }
.Where(s => !string.IsNullOrEmpty(s))
.ToArray();
var numberOfParts = dayParts.Length;
string result;
if (numberOfParts < 2)
result = dayParts.FirstOrDefault() ?? string.Empty;
else
result = string.Join(", ", dayParts, 0, numberOfParts - 1) + " and " + dayParts[numberOfParts - 1];
return result.UppercaseFirst();
}
Stolen from https://codereview.stackexchange.com/questions/24995/convert-timespan-to-readable-text .
I am currently designing a ticket system for my place of work.
Currently, I have most of it working except one small part. It is setup to automatically send it to the person that is responsible for fixing it. After it tells the user their Unique ID and the estimated date it should be finished. The only problem is People work different shifts. The things I want it to be able to do is
If a ticket is put in before the persons shift, it adjusts to the time they come in for their shift.
If a ticket is put in after a persons shift, adjusts it to the next day and the start of the persons shift.
If the ticket takes longer than the time remaining in the shift, use the time remaining in the shift and the remaining in the following day.
Be able to add time from previous tickets that are not completed and maintain the work schedule. (Currently working except maintaining work schedule)
For example:
First shift comes in at 7:00 am and someone puts in a ticket at 3:00 am, it should go to 7:00 am and than adjust the amount of time needed.
First shift leaves at 3:30pm and someone puts in a ticket at 3:00 pm that takes roughly an hour to complete, it should finish the 30 minutes in the day and go 30 minutes into the following day.
The code I currently have to try to handle this
if (DateTime.Now.AddMinutes(sum).Hour <= 8)
{
MessageBox.Show("Too early");
var now = DateTime.Now;
var tomorrow8am = now.AddDays(0).Date.AddHours(8);
double totalHours = (tomorrow8am - now).TotalHours;
MessageBox.Show("totalHours=" + totalHours);
var today8am = now.Date.AddHours(8).Hour;
EstimatedCompleteDate = DateTime.Today.Month + "/" + DateTime.Today.AddDays(0).Day + "/" + DateTime.Today.Year + " " + DateTime.Now.AddHours(totalHours).AddMinutes(timetoadd).ToLongTimeString();
MessageBox.Show(now.ToString() + Environment.NewLine + tomorrow8am.ToString() + Environment.NewLine + totalHours.ToString());
MessageBox.Show(now.AddHours(totalHours).AddMinutes(timetoadd).Hour.ToString());
if (DateTime.Now.AddHours(totalHours).AddMinutes(timetoadd).Hour > 15)
{
double hourstoadd = 0;// = timetoadd / 60;
do
{
hourstoadd++;
timetoadd = timetoadd - 60;
}
while (timetoadd > 60);
var remaining = hourstoadd;
int i = 0;
MessageBox.Show(remaining.ToString());
do
{
if (remaining > 0)
{
MessageBox.Show("Remaining1: " + remaining.ToString());
MessageBox.Show("Remaining - totalHours" + (remaining - totalHours).ToString());
i++;
EstimatedCompleteDate = DateTime.Today.Month + "/" + DateTime.Today.AddDays(i).Day + "/" + DateTime.Today.Year + " " + DateTime.Now.AddHours(totalHours + remaining).AddMinutes(timetoadd + now.Minute).ToLongTimeString();
remaining = remaining - 8;
}
}
while (remaining > 0);
please excuse the messagebox's I am using to give some feedback to me.
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
I need to show also the minutes, actually I use this code for show the seconds, but also need the minutes
TimeSpan ts = stopwatch.Elapsed;
Console.WriteLine("File Generated: " + _writer.getBinaryFileName(filePath, Convert.ToInt32(logSelected)) + " in " + "{0}.{1:D2}" + "seconds",
ts.Seconds,
ts.Milliseconds/10 + "\n"
);
how can I do?
You should use:
ts.ToString("mm\\:ss\\.ff")
this will give you minutes, seconds and the hundredths of a second in a time interval.
also take a look at http://msdn.microsoft.com/en-us/library/ee372287.aspx
EDITED:
well if you want minutes be your biggest unit you can do the following:
string.Format("{0}:{1}", Math.Floor(ts.TotalMinutes), ts.ToString("ss\\.ff"))
The TimeSpan.ToString() method in .NET 4.0 has an overload that lets you specify the format.
To display minutes and seconds:
TimeSpan elapsed = GetElapsedTime(); // however you get the amount of time elapsed
string tsOut = elapsed.ToString(#"m\:ss");
To include the milliseconds, you would write:
string tsOut = elapsed.ToString(#"m\:ss\.ff");
Note, however, that this won't do what you expect if the total timespan is more than 60 minutes. The "minutes" value displayed will be elapsed.Minutes, which is basically the same as ((int)elapsed.TotalMinutes) % 60). So if the total time was 70 minutes, the above will show 10:00.
If you want to show the total minutes and seconds reliably, you have to do the math yourself.
int minutes = (int)elapsed.TotalMinutes;
double fsec = 60 * (elapsed.TotalMinutes - minutes);
int sec = (int)fsec;
int ms = 1000 * (fsec - sec);
string tsOut = String.Format("{0}:{1:D2}.{2}", minutes, sec, ms);
I've coded this way:
using System.Diagnostics;
...
Stopwatch watch = new Stopwatch();
watch.Start();
// here the complex program.
...
watch.Stop();
TimeSpan timeSpan = watch.Elapsed;
Console.WriteLine("Time: {0}h {1}m {2}s {3}ms", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds);
//try it
Stopwatch sw = new Stopwatch();
sw.Start();
Thread.Sleep(10382);
sw.Stop();
Console.Write(sw.Elapsed.Duration());
Review the documentation for TimeSpan, the struct returned by stopwatch.Elapsed. You want either the Minutes or TotalMinutes property.
If you're measuring a 62 minute span, ts.Minutes will return 2, and ts.TotalMinutes will return 62.
TimeTakenOutput.Text = "0" + myStopWatch.Elapsed.Minutes.ToString()
+ ":" + myStopWatch.Elapsed.Seconds.ToString() + "mins";
ts.Minutes