I'm trying to get the date into a string in C#. I want the format of:
2011.02.14
Which is, YYYY.MM.DD
Can someone please let me know the command for this? And also is there a way to do like Date(-1)?
Thanks.
System.DateTime.Now.ToString("yyyy.MM.dd");
System.DateTime.Now.AddDays(-1)
For the first:
string s = DateTime.Now.ToString("yyyy.MM.dd");
For the second, you'd need to be explicit about what Date(-1) should return, but I expect it involves var foo = someDate.Add(timespan); or var foo = someDate.Add{SomeInterval}(delta);
Declare a string like :
string mydate;
myDate = DateTime.Now.ToString("yyyy.MM.dd");
messagebox.show(myDate);
You can do that using DateTIMe's ToString method, more info on MSDN
Related
I have looked around for this, but I'm not sure it's possible with string interpolation (I'm using VS2015).
string sequenceNumber = $"{fieldValuePrefix.ToUpper()}{separator}{similarPrefixes + 1:D4}";
Is there any way to make D4 a variable ? Some say yes, some no. Apparently, VS2015 C#6.0 is able to do it.
This works, it will return a string like WMT-0021, depending on fieldValuePrefix (WMT), separator (-) and the value of similarPrefixes (20). But I'd like the "D4" part to be a method argument instead of hardcoded in there.
Any ideas ?
You can, but you have to use explicit ToString call like this:
string format = "D4";
string sequenceNumber =
$"{fieldValuePrefix.ToUpper()}{separator}{(similarPrefixes + 1).ToString(format)}";
I have two values, I want to cast these values into a text box. The way I tried is mentioned below
string time="00";
int Result ="02";
textresult.Text=result+' '+time;//first way error result
textresult.Text=(CAST(Result AS varchar(50))+' '+CAST(time AS varchar(50)))//second way..syntax error.
I need output as 02:00 format in text box. Please suggest a way to solve this????
Try this:-
string time = "00";
int Result = 02;
textresult.Text=Result.ToString("D2") + ":" + time;
Try below.
textresult.Text=string.Format("{0}:{1}",Result.ToString("D2"),time);
Your code reports syntax error because there is. It seems you are using C# like sql syntax!
This might help.
string time="00";
int Result =02;
textresult.Text = String.Format("{0}:{1}",Result.ToString("D2"),time);
Fiddle link
I have the following code inside my asp.net vmc web application :-
var getNumbers = (from t in ut.newTag
where char.IsDigit(t)
select t).ToString();
tech.PartialTag = Convert.ToInt32(getNumbers);
but i am getting the following exception :-
Input string was not in a correct format.
so can anyone advice how i can solve this issue??
getNumbers is a string, containing type name of string enumerator It will look like
"System.Linq.Enumerable+WhereSelectArrayIterator`1[System.String,System.String]"
You obviously can't convert that type name to integer. If you want to try parse newTag and assign it to PartialTag if there is an integer:
int value;
if (Int32.TryParse(ut.newTag, out value))
tech.PartialTag = value;
There's a ctor of String taking a char[] as parameter, so
var getNumbers = new String((from t in ut.newTag
where char.IsDigit(t)
select t).ToArray());
tech.PartialTag = Convert.ToInt32(getNumbers);
Difference with Sergey's answer :
if your input is 1A2 for example, Sergey's solution won't accept the input.
But my solution (based on yours) will take 12.
So, it depends on what you need (I think Sergey's one is clearer, it just rejects non integers inputs).
I am trying to convert an object (coming from a SQL server), into a integer so I can format the number to have the correct amount of zero's in front of it.
For example:
If I were to have 25.6, I would need it to be 0025.6.
Now I have looked online on how to do this, but the methods that I have seen people post are not working for me. I am not entirely sure why. I am trying to format GlobalVariables.grossweightafter. I read the value GlobalVariables.grossweight from the SQL server, but then when I TryParse it, it loses its value. The code I have is below:
while (TransferRecord.Read())
{
//Pulling data from the SQL server. getting data for every line of code as specified.
GlobalVariables.baledate = TransferRecord["keyprinter_datetime"];
GlobalVariables.baleline = TransferRecord["pulp_line_id"];
GlobalVariables.baleid = TransferRecord["bale_id"];
GlobalVariables.grossweight = TransferRecord["bale_gross_weight"];
GlobalVariables.grossweightflag = TransferRecord["gross_value_flag"];
GlobalVariables.baleairdrypercent = TransferRecord["bale_airdry_pct"];
GlobalVariables.airdryflag = TransferRecord["airdry_value_flag"];
//Converting the date, and the baleid to fit in the string.
DateTime.TryParse(GlobalVariables.baledate.ToString(), out GlobalVariables.baledateafter);
int.TryParse(GlobalVariables.baleid.ToString(), out GlobalVariables.baleidafter);
int.TryParse(GlobalVariables.grossweight.ToString(), out GlobalVariables.grossweightafter);
GlobalVariables.grossweightafter.ToString("0000.0");
//Calling the WriteData method.
WriteData();
}
So I was wondering if anyone can catch what I am doing wrong, or they can help me out on the correct way to go about this.
What #Hans Passant was saying is that you need to assign the value returned from .ToString. That line should be:
GlobalVariables.grossweightafter = GlobalVariables.grossweightafter.ToString("0000.0");
The last lines should be
if(int.TryParse(GlobalVariables.grossweight.ToString(), out GlobalVariables.grossweightafter))
{
string grossWeightAfter = GlobalVariables.grossweightafter.ToString("0000.0");
//you need to save the string returned from the ToString-method somewhere or it will be lost.
///Alternatively, if GlobalVariables can contain strings aswell:
GlobalVariables.grossweightafter = GlobalVariables.grossweightafter.ToString("0000.0");
}
else
{
//React on value not being an int
}
Maybe you should try to use double.TryParse() method instead of int.TryParse(), because int does not have fractional part?
Also, you need to store ToString() result to a string variable. Your code should be like this:
GlobalVariables.grossweightafterstring = GlobalVariables.grossweightafter.ToString("0000.0");
Is there any way to make
TypeDescriptor.GetConverter.ConvertFromString convert to DateTime using a custom format e.g. "2011-04-21 13-03-56"?
If not, is there any DateTime-format out there that can be applied to a folder name (/,\,:,etc. are not allowed as you know)?
Help is very much appreciated. Thanks in advance
Random-I-Am
Edit:
Since my request still seems to not be understood correctly I am again trying to elaborate on my question. My users are creating folders with specific names. For example "1000_Link_Topic1_2011-01-25 14-12-10". They are free to combine their information as they like and omit information where needed. They don't even have to care about case sensitivity. So I could face another folder named "1000_link_Topic2".
What I have is a single class with a single property for each possible fragment of information. In this case I would have (Since I had to find a way of checking each properties default value regardless of the property type I am using nullable types):
Short? short_val;
EContentType? enum_val;
String string_val;
DateTime? datetime_val;
My code obviously splits the folder name at "_" and then tells for each fragment to which of the above property types it belongs. As soon as I know the corresponding type I am trying to convert to the Type, lets say t, using TypeDescriptor.GetConverter(t).ConvertFromString(info_frag[i]). I hope you now understand why I cannot use another conversion Method.
The code works for all the types mentioned above. My problem is to find a custom DateTime format that can be used on a folder name. All of the formats I know are using colons to separate hours from minutes and seconds.
What I want is a way to convert from a custom DateTime-format to a DateTime-object using TypeDescriptor.GetConverter.ConvertFromString. If that is not possible I either need to find a standard DateTime-format which can be assigned as a folder name without any further conversion or somehow extend the built-in DateTime-formats by my custom format. If it is going to be the latter I do not care about being able to use seconds or minutes. Hours will do the job.
Thanks again for being as patient as you are and helping me out with this one. Feel free to ask as many further questions as you like. I hope you can help me getting this one to work.
Random-I-Am
I have looked into your problem a little and found that the standard DateTimeTypeConverter uses DateTime.Parse internally which doesn't listen to CurrentCulture info at all. Instead you can trick the conversion process with your own TypeConverter!
I do not know how to attach the new typeconverter to the existing DateTime structure, if you even can, so I made a miniture AdvancedDateTime structure .. which is empty. Noone said your custom TypeConvert should even return such a thing! This one returns a regular DateTime. I provided the code below:
public class CustomDateTimeTypeConverter : TypeConverter
{
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return DateTime.ParseExact(value.ToString(), "yyyy-MM-dd HH-mm-ss", culture);
}
}
[TypeConverter(typeof(CustomDateTimeTypeConverter))]
struct AdvancedDateTime
{
}
[TestFixture]
public class DateTime
{
[Test]
public void TypeConvert_StrangeFormat_ConvertsWithoutProblem()
{
string datetime = "2011-04-21 23-12-13";
TypeConverter converter = TypeDescriptor.GetConverter( typeof (AdvancedDateTime) );
var convertedFromString = converter.ConvertFromString(datetime);
Assert.AreEqual(new DateTime(2011,4,21, 23,12,13), convertedFromString);
}
}
Try this
string m_strDate = DateTime.Now.ToString("MM/dd/yyyy");
m_strDate = m_strDate.Replace("/", "");
Append this m_strDate to your folder
A sample i used for text file is as follows
strPath += "/FileHeader_" + m_strDate + ".txt";
Check this sample
DateTime dt=new DateTime(1990,5,6);
Console.WriteLine(TypeDescriptor.GetConverter(dt).ConvertTo(dt, typeof(string)));
string myStr="1991-10-10";
Console.WriteLine(TypeDescriptor.GetConverter(dt).ConvertFrom(myStr));
The sample code i written just to display as per you need try as per your requirement
string s = "Folder";
DateTime dt = new DateTime(1990, 5, 6);
string str = TypeDescriptor.GetConverter(dt).ConvertTo(dt, typeof(string)).ToString();
string myStr = "1991-10-10";
string str1 = TypeDescriptor.GetConverter(dt).ConvertFrom(myStr).ToString();
s = s + str1.Replace("/", "").Replace(":", "");
textBox1.Text = s;