How to implement DateTime [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Can anyone please show me how do I implement DateTime on this code? Tried to google around but still confusing on this code.
public double CalcLastCouponDate(DateTime dtmBaseDate, DateTime dtmLastDate, int intCouponTermMonths, int intFixedCouponDay, string strOddLastCouponType)
{
int i = 0;
DateTime dtmLastCoupon;
{
if (strOddLastCouponType == "S")
{
return dtmLastCoupon = DateAdd("M", -intCouponTermMonths, dtmLastCoupon); // How to convert DateAdd to C#
}
else
{
return dtmLastCoupon = DateAdd("M", -2 * intCouponTermMonths, dtmLastCoupon); // How to convert DateAdd to C#
}
}
}
public bool IsEndDayofMonth(DateTime DateIn)
{
int intLastDay = 0;
bool IsEndDay = false;
intLastDay = CalcEndDayofMonth(Year(DateIn), Month(DateIn)); // Convert Year, Month to C#
if (intLastDay == Day(DateIn)) // Convert Day to C#
{
IsEndDay = true;
}
else
{
IsEndDay = false;
}
return IsEndDay;

Assuming DateAdd has normal semantics it would probably look something like this:
public DateTime CalcLastCouponDate(DateTime dtmBaseDate, DateTime dtmLastDate, int intCouponTermMonths, int intFixedCouponDay, string strOddLastCouponType)
{
return (strOddLastCouponType == "S") ?
dtmLastDate.AddMonths(-intCouponTermMonths) :
dtmLastDate.AddMonths(-2 * intCouponTermMonths);
}
public bool IsLastDayOfMonth(DateTime dateIn)
{
return dateIn.Day == DateTime.DaysInMonth(dateIn.Year, dateIn.Month);
}
Etc.

can u give a clear idea what you are trying to achieve.
have a look on the below links I think you may find your need.
Custom date time formats
DateTime methods

Related

cannot convert from 'double' to 'System.ReadOnlySpan<char>' error when trying to use `TryParse` [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm currently learning C# and I'm having troubles. I'm getting cannot convert from 'double' to 'System.ReadOnlySpan<char>' error when I try to use !double.TryParse
static double userDouble, correctDouble;
static void someMethod() {
Console.Write(someStringOfDoubles);
while(!double.TryParse(userDouble, out _)) {
try {
userDouble= Double.Parse(Console.ReadLine());
}
catch {
Console.WriteLine($"{Convert.ToString(userDouble)} is an invalid input\n\n");
}
}
// checks if the userDouble is correct or not.
if (Math.Round(correctDouble, 2) == userDouble) {
Console.WriteLine("You are Correct!\n");
}
else {
Console.WriteLine("You are Incorrect.");
}
}
What should it do: Check if userDouble is a valid double and not letter(s)/word(s).
I also tried:
while(!double.TryParse(Console.ReadLine(), out userDouble)) {
Console.WriteLine($"{Convert.ToString(userDouble)} is an invalid input\n\n");
}
but this gives me No overload for method 'TryParse' takes 1 arguments
Any help would be much appreciated!
You need to get console value in string variable first then check it with double.TryParse(...). Try like below.
string s = Console.ReadLine();
while(!double.TryParse(s, out userDouble)) {
Console.WriteLine($"{s} is an invalid input\n\n");
s = Console.ReadLine();
}
Below attempt of yours must work without any error. But only problem you will face is it will write 0 is an invalid input for evert input because double.TryParse will set userDouble = 0 when value from Console.ReadLine() are not double.
while(!double.TryParse(Console.ReadLine(), out userDouble)) {
Console.WriteLine($"{Convert.ToString(userDouble)} is an invalid input\n\n");
}

Convert a string to Double in C# [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I just wrote a method to convert a string to double. It does what it's suppose to do, but it seems too long and I'm thinking there's a better way of writing it. Please review and suggest a better way or point out why this is not good for production code.
static double ConvertStringToDouble(string input, int rounding)
{
string[] split = input.Split('.');
double wholeNumber = 0.0;
if (split.Length > 0 && Int32.TryParse(split[0], out int temp))
wholeNumber = (double)temp;
double decimalNumber = 0.0;
if (split.Length > 1)
{
string decimalString = (split[1].Length < rounding) ? split[1] : split[1].Substring(0, rounding);
if (Int32.TryParse(decimalString, out int dec))
decimalNumber = (double)dec / Math.Pow(10, decimalString.Length);
}
return wholeNumber + decimalNumber;
}
This is the updated method now. Thanks all for the contributions
static double ConvertStringToDouble(string input, int rounding)
{
if (double.TryParse(input, out double value))
return Math.Round(value, rounding);
else return 0.0;
}
.Net has built in functionality for this, its called Double.TryParse. Double.Parse also exists, but its recommended to use the Try variant, as it won't throw exceptions if the number is not parseable into a double. You can use the method like this
string stringToParse = "1.7346"
if (Double.TryParse(stringToParse, out double parsedDouble))
{
//do something with the double here
}
else
{
//failed to parse, error logic here
}
You can just use double.Parse and double.TryParse methods, I prefer to use them like this:
string myString = "1.05";
// This throws exception:
double myParsedDouble = double.Parse(myString);
// This gives you more control over the conversion:
double? myResult = null;
if (double.TryParse(myString, out double _myResult))
myResult = _myResult;
if (myResult == null)
{
throw new ArgumentException("Not a valid double!");
}

How to return multiple values in C# 7? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Is it is possible to return multiple values from a method natively?
What do you mean by natively?
C# 7 has a new feature that lets you return more than one value from a method thanks to tuple types and tuple literals.
Take the following function for instance:
(string, string, string) MyCoolFunction() // tuple return type
{
//...
return (firstValue, secondValue, thirdValue);
}
Which can be used like this:
var values = MyCoolFunction();
var firstValue = values.Item1;
var secondValue = values.Item2;
var thirdValue = values.Item3;
Or by using deconstruction syntax
(string first, string second, string third) = MyCoolFunction();
//...
var (first, second, third) = MyCoolFunction(); //Implicitly Typed Variables
Take some time to check out the Documentation, they have some very good examples (this answer's one are based on them!).
You are looking for Tuples. This is an example:
static (int count, double sum) Tally(IEnumerable<double> values)
{
int count = 0;
double sum = 0.0;
foreach (var value in values)
{
count++;
sum += value;
}
return (count, sum);
}
...
var values = ...
var t = Tally(values);
Console.WriteLine($"There are {t.count} values and their sum is {t.sum}");
Example stolen from http://www.thomaslevesque.com/2016/07/25/tuples-in-c-7/
You can also implement like this:
public class Program
{
public static void Main(string[] args)
{
var values=GetNumbers(6,2);
Console.Write(values);
}
static KeyValuePair<int,int> GetNumbers(int x,int y)
{
return new KeyValuePair<int,int>(x,y);
}
}

Creating an array of all ASCII characters in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am currently creating a program that uses arrays to categorize ASCII characters in a text document. I am stuck when it comes to creating the array itself, which is a critical part to the project's functionality. It is also suggested that I make the array out of charfrequency objects, which I know my code for is not quite right for this particular project. I used the code from another similar project, but am unsure how to translate it to a project that reads text from a file. I have included my charfrequency class code for reference as to a general idea of what I'm trying to do. I also need to display the results in a format like this:
H(72) = 1
e(101) = 1
l(108) = 2
o(111) = 1
.(46) = 1
I do not understand programming very well, so detailed explanations with relatively simple terms would be very helpful.
{
public class CharFrequency
{
private char m_character;
private long m_count;
public CharFrequency(char ch)
{
Character = ch;
Count = 0;
}
public CharFrequency(char ch, long charCount)
{
Character = ch;
Count = charCount;
}
public char Character
{
set
{
m_character = value;
}
get
{
return m_character;
}
}
public long Count
{
get
{
return m_count;
}
set
{
if (value < 0)
value = 0;
m_count = value;
}
}
public void Increment()
{
m_count++;
}
public override bool Equals(object obj)
{
bool equal = false;
CharFrequency cf = new CharFrequency('\0', 0);
cf = (CharFrequency)obj;
if (this.Character == cf.Character)
equal = true;
return equal;
}
public override int GetHashCode()
{
return m_character.GetHashCode();
}
public override string ToString()
{
String s = String.Format("Character '{0}' ({1})'s frequency is {2}", m_character, (byte)m_character, m_count);
return s;
}
}
}
Since Unicode matches ASCII codes you can just select ASCII range with Enumerable.Range:
var allAscii = Enumerable.Range('\x1', 127).ToArray();
Note that C#/.Net uses UTF-16 (C# and UTF-16 characters) to represent char, but if you only looking for ASCII range it is not a problem (as ASCII covers characters with codes 1-127 it will not conflict with surrogate pairs which are encoded into 2 char in a string).
You can simply store your character frequencies in Dictionary<char, long>.
Perhaps you want to look at this:
http://stackoverflow.com/questions/3665757/c-sharp-convert-char-to-int
If it were me I would create an array in which I stored the character occurances like this:
long[] charCount = new long[256];
And then each time I see a character convert it to its integer value with something like:
int idx = (int)char.GetNumericValue(c);
And then count that character occurance like:
charCount[idx]++;

Check if a string contains not defined characters [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a pre defined string as Follows.
string preDefined="abc"; // or i can use char array in here
string value="ac";
string value1="abw";
I need some function to compare value with preDefined.
(value.SomefunctionContains(preDefined)
this function needs to return
value -> true;
value1 -> false
I knew that i can't use contains() or Any(). so plz help
You are just looking for if value has any character that is not in predefined, so this should do it:
!value.Any(x => !predefined.Contains(x))
Or it's more clear using All:
value.All(predefined.Contains);
private bool SomeFunction(string preDefined, string str)
{
foreach (char ch in str)
{
if (!preDefined.Contains(ch))
{
return false;
}
}
return true;
}
You can implement the following method to get the result :
private static bool DoesContain(string predefined, string value)
{
char[] c_pre = predefined.ToCharArray();
char[] c_val = value.ToCharArray();
char[] intersection = c_pre.Intersect(c_val).ToArray();
if (intersection.Length == c_val.Length) {
return true;
}
else {
return false;
}
}
Please not that this solution is a generalized implementation. IT also returns true even if the characters are not in the same order, unless ther include all.

Categories