Convert int to string in specific format - c#

I have a int which I want to convert to string in specific format.
For example,
-1 to -01:00
It is easy if I have positive number (i.e 1 to 01:00). I can use following code:
var time = 6;
var convertTime = "0" + time + ":00";
Output:
06:00
I am not sure how to achieve same with negative number.
var time = -6;
var convertTime = /* what to do here */ + time + ":00";
Desired Output:
-06:00

Just use string.Format for that
int time = -6;
var convertTime = string.Format("{0:00}:00", time);
Or if you have C# 6 you can do an interpolated string.
var convertTime = $"{time:00}:00";

var time = -6;
var convertTime = (time < 0 ? "-" : String.Empty) + Math.Abs(time).ToString("D2") + ":00";

var time = (myInt*100).ToString("00:00");
Or if using C# 6 (VS2015):
var input = -6;
var time = $"{input:00}:00";

Here's an example utilizing TimeSpan.
public void TestTimeSpan()
{
var ts = new TimeSpan(-1, 0, 0);
var s = string.Format("{0}{1:hh\\:mm}", ts < TimeSpan.Zero? "-": string.Empty, ts);
Assert.AreEqual("-1:00", s);
}

Related

how to show number of digits on users's request?

for example: if a string value is "123456.7890" .
if user enters the length 6 and the other value 2 for the decimal place.
the output value should be like "123456.78"
if user enters the length 5 and the other value 3 for the decimal place.
the output value should be like "12345.789"
string s = "123456.7890";
string a = string.Format("{0, 2:F2}", s);
int index = a.IndexOf('.');
a = a.Substring(index, (a.Length-index));
One approach could be like this:
NOTE: If the string's length is less than the number of characters you're taking, code will throw an exception ArgumentOutOfRangeException
int LeftPlaces = 4;
int RightPlaces = 2;
String Input = "123456.7890";
String[] Splitted = Input.Split('.');
String StrLeft = Splitted[0].Substring(0, LeftPlaces);
String StrRight = Splitted[1].Substring(0, RightPlaces);
Console.WriteLine(StrLeft + "." + StrRight);
Output: 1234.78
The most crude and direct way would be:
var length = 5;
var decimalPlaces = 2;
var s = "123456.7890";
var data = s.Split('.');
var output1 = data[0].Substring(0, length);
var output2 = data[1].Substring(0, decimalPlaces);
var result = output1 + "." + output2;
If you want to do this without strings, you can do so.
public decimal TrimmedValue(decimal value,int iLength,int dLength)
{
var powers = Enumerable.Range(0,10).Select(x=> (decimal)(Math.Pow(10,x))).ToArray();
int iPart = (int)value;
decimal dPart = value - iPart;
var dActualLength = BitConverter.GetBytes(decimal.GetBits(value)[3])[2];
var iActualLength = (int)Math.Floor(Math.Log10(iPart) + 1);
if(dLength > dActualLength || iLength > iActualLength)
throw new ArgumentOutOfRangeException();
dPart = Math.Truncate(dPart*powers[dLength]);
iPart = (int)(iPart/powers[iActualLength - iLength]);
return iPart + (dPart/powers[dLength]);
}
Client Call
Console.WriteLine($"Number:123456.7890,iLength=5,dLength=3,Value = {TrimmedValue(123456.7890m,5,3)}");
Console.WriteLine($"Number:123456.7890,iLength=6,dLength=2,Value = {TrimmedValue(123456.7890m,6,2)}");
Console.WriteLine($"Number:123456.7890,iLength=2,dLength=4,Value = {TrimmedValue(123456.7890m,2,4)}");
Console.WriteLine($"Number:123456.7890,iLength=7,dLength=3,Value = {TrimmedValue(123456.7890m,7,3)}");
Output
Number:123456.7890,iLength=5,dLength=3,Value = 12345.789
Number:123456.7890,iLength=6,dLength=2,Value = 123456.78
Number:123456.7890,iLength=2,dLength=4,Value = 12.789
Last call would raise "ArgumentOutOfRangeException" Exception as the length is more than the actual value

How to change a string format like 2d30m to timespan?

I dont know what is this format called like 2d30m in programming language. But, I see some Jquery plugin or Youtube's jump to time url like &t=3m11s using this time format. It's hard to google because I dont know the excat keyword.
So, I want to use this kind of format and translated into TimeSpan object in C#. How can I achieve this?
Right now I'm trying to extract the value from string by this code
public static void Main()
{
String str = "2d30m";
int day = 0, minute = 0;
//Get Day
day = Helper(str, "d");
//Get Minute
minute = Helper(str, "m");
//Create timespan
var myTimeSpan = new TimeSpan(days: day, hours: 0, minutes: minute, seconds: 0);
Console.Write(myTimeSpan);
}
public static int Helper(string input, string timeCode)
{
int output = 0;
int indexOf = input.LastIndexOf(timeCode, StringComparison.OrdinalIgnoreCase);
if (indexOf > 0)
{
string strTime = input.Substring(Math.Max(0, indexOf - 2), 2);
Console.WriteLine(strTime);
strTime = System.Text.RegularExpressions.Regex.Replace(strTime, "[^0-9.]", ""); // remove all alphabet
output = Convert.ToInt32(strTime);
}
return output;
}
You can use TimeSpan.ParseExact:
var str = "2d30m";
// d matches both 1 and 2 digit days
// \d means literal "d"
// m matches both 1 and 2 digit minutes
// \m is literal "m"
var timeSpan = TimeSpan.ParseExact(str, #"d\dm\m", CultureInfo.InvariantCulture);
Just use Regex.Match against the entire string. Easy enough to get the groups:
public static void Main()
{
var str = "2d30m";
//Regex match and find the 2 & 30
var matches = Regex.Match(#"^(\d+)d(\d+)m$", str);
//Get Day
var day = int.Parse(matches.Groups[1].Value);
//Get Minute
var minute = int.Parse(matches.Groups[2].Value);
//Create timespan
var myTimeSpan = new TimeSpan(days: day, hours: 0, minutes: minute, seconds: 0);
Console.Write(myTimeSpan);
}
See dotnetfiddle here.

How to concatenate integer with string in C#?

I am developing a Console application for converting the time from 12 hours format to 24 hours format:
input: 02:03:34PM expected output:14:03:34
But I am getting 14:3:34
Below is my code snippet:
string[] arr_temp = Console.ReadLine().Split(':');
string time = arr_temp[2].ToUpper().Contains("AM") ? "AM" : "PM";
string sec=string.Empty;
for (int i = 0; i < 2; i++)
{
sec+= arr_temp[2][i];
}
int _hour = Int32.Parse(arr_temp[0])==0?0: Int32.Parse(arr_temp[0]);
int _minute = Int32.Parse(arr_temp[1]) == 0 ? 0 : Int32.Parse(arr_temp[1]);
int _sec = Int32.Parse(sec)==0?0: Int32.Parse(sec);
_hour = (time == "PM") ? _hour += 12 : _hour += 0;
_hour = (_hour < 10) ? '0' + _hour : _hour;
_minute = (_minute < 10) ? '0' + _minute : _minute;
_sec = (_sec < 10) ? '0' + _sec : _sec;
I am not getting the expected output.
Please suggest.
Seems a bit complicated to me as there's a much simpler way to display your DateTime variable to either 12 or 24 hours format.
First you will have to convert your string to a valid DateTime object. There are parsing methods which you can use, but you will have first to validate the input string returned by the user as a valid date.
Use the following code in order to convert your string to DateTime:
string dateString = "03/01/2009 10:00 AM";
DateTime date = DateTime.Parse(dateString);
DateTime.Parse will throw an exception if input string is not in the right format. In order to make sure this doesn't happen, use DateTime.TryParse instead.
string dateString = "03/01/2009 10:00 AM";
DateTime dateTime;
if (DateTime.TryParse(dateString , out dateTime))
{
Console.WriteLine(dateTime);
}
Then you can display the DateTime variable and format it the way you want.
DateTime dateTime = DateTime.Now;
string str12Format = dateTime.ToString("hh:mm:ss tt"); //12 hours format
string str24Format = dateTime.ToString("HH:mm:ss tt"); //24 hours format
_hour in your code is an integer. You cannot concatenate string to an integer. But the reverse is possible.
So you should use this instead :
int _hour = Int32.Parse(arr_temp[0])==0?0: Int32.Parse(arr_temp[0]);
int _minute = Int32.Parse(arr_temp[1]) == 0 ? 0 : Int32.Parse(arr_temp[1]);
int _sec = Int32.Parse(sec)==0?0: Int32.Parse(sec);
_hour = (time == "PM") ? _hour += 12 : _hour += 0;
String _hourS = (_hour < 10) ? '0' + _hour : _hour;
String _minuteS = (_minute < 10) ? '0' + _minute : _minute;
Try using DateTime.TryParseExact followed by ToString, do not repeat Microsoft and reinvent the wheel:
string source = Console.ReadLine();
DateTime date;
// DateTime.TryParseExact supports many formats; that's why "12:34AM" will be accepted
// DateTimeStyles.AllowWhiteSpaces let us be nice and allow, say "11 : 34 : 47 PM"
if (DateTime.TryParseExact(
source,
new string[] {"h:m:stt" , "h:mtt", "htt", "H:m:s", "H:m", "H"},
CultureInfo.InvariantCulture, // or CultureInfo.CurrentCulture
DateTimeStyles.AssumeLocal | DateTimeStyles.AllowWhiteSpaces,
out date))
Console.WriteLine(date.ToString("HH:mm:ss"));
else
Console.WriteLine($"Sorry, {source} is not a valid date");
Just pass you input
public static TimeSpan ConvertToAMPM(DateTime date)
{
return TimeSpan.Parse(date.ToString("h:mm tt",
CultureInfo.InvariantCulture));
}
public static TimeSpan ConvertTo24Hour(string time)
{
var cultureSource = new CultureInfo("en-US", false);
var cultureDest = new CultureInfo("de-DE", false);
var dt = DateTime.Parse(time, cultureSource);
return TimeSpan.Parse(dt.ToString("t", cultureDest));
}
The other answers so far mostly address the example of handling a DateTime, but they do not explain why your code breaks.
What you are trying to do is to add a leading zero to an int variable just as you'd do it with a string.
The problem is that the internal representation of an int is just the number itself, and it carries no format information. As such, it cannot store information about leading zeros. This can only be done by using string, which do not represent a number but a collection of characters.
So the essence is that you need to see the data and its representation as two separate things. In general it's best to keep the data in its native form and only convert it at the very last moment when needed for display. This also allows you to respect cultural differences of the display representation.
Many basic data types (including int and DateTime etc.) are formattable. What this means is that they can be converted to a string (display) representation with respect to a pattern describing how this representation should be. For int, such a pattern can define that it needs to have a leading zero like so:
string _hourDisplay = _hour.ToString("00");
Hi Nishank, Use this code :
string[] arr_temp = Console.ReadLine().Split(':');
string time = arr_temp[2].ToUpper().Contains("AM") ? "AM" : "PM";
string sec = arr_temp[2].Substring(0, 2);
string _hour = "";
if (time == "PM" && Int32.Parse(arr_temp[0]) < 12)
_hour = (Int32.Parse(arr_temp[0]) + 12).ToString("D2");
else if (time == "AM" && Int32.Parse(arr_temp[0]) == 12)
_hour = "00";
else
_hour = Int32.Parse(arr_temp[0]).ToString("D2");
string _minute = Int32.Parse(arr_temp[1]) == 0 ? "00" : Int32.Parse(arr_temp[1]).ToString("D2");
string _sec = Int32.Parse(sec) == 0 ? "00" : Int32.Parse(sec).ToString("D2");
string outputTime = _hour + ":" + _minute + ":" + _sec + "" + time;

Add zero padding to string using $"{x:Dn}" notation

I am a big fan of the new $"" notation to format strings in c#. Hence I would like to use this notation to pre-pend some leading zero's to an integer.
var i = 10;
var s = $"{i:D4}";
This does the job well en results in 0010.
But what if the amount of zero's or the total length is variable. How do I accomplish that using this new notation ?
I'm looking for somthing like :
var TotalLength = 4; // IRL it would be a calculated value.
var format = "D" + TotalLength.ToString();
var i = 10;
var s = $"{i:format}";
variant I've tried but does not work either.
$"{i:{format}}"
Any suggestions ?
Or - mixing your something like and Rob's method:
var TotalLength = 4; // IRL it would be a calculated value.
var format = TotalLength.ToString("'D'0");
var i = 10;
var s = $"{i.ToString(format)}";
Based on the suggestions given I've made two extension methods :
public static String GetDnFormat(this int i)
{
return ((int)Math.Log10(i) + 1).ToString("'D'0");
}
public static String ToDnFormat(this int i, int source)
{
var format = source.GetDnFormat();
return i.ToString(format);
}
Usage :
var Page = 10;
var PageCount = 124;
var PageLabel = $"{Page.ToDnFormat(PageCount)}/{PageCount}"; // result : 010/124

How to calculate remaining minutes to "next" half an hour or hour?

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();
}

Categories