I am getting a result like this "PR242714031213" from a SQL query. This is basically a string PR + ssmmHHddMMyy. I need to extract and format it to a simple date ddMMyyyy.
I am using the following snippet with substrings which is working:
string rawDate = (string)lastProjaddedDate.ExecuteScalar();
string year= rawDate.Substring(12,2);
string month=rawDate.Substring(10,2);
string day=rawDate.Substring(8,2);
string date = day + "/" + month + "/" +"20"+ year;
Label4.Text =date;
I am wondering if I can simplify the code to get the ddMMyyyy out of it.
PS: I know I need to change the way it is codified in the DB to avoid problems in few decades but lets start to simplify it.
You can do:
Step - 1: Strip `PR` from the string
Step - 2: Parse to .Net `DateTime` object
Step - 3: Format to required format
Code :
string rawDate = "PR242714031213";
rawDate = rawDate.Substring(2);
DateTime dt;
if (!DateTime.TryParseExact(rawDate,
"ssmmHHddMMyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//invalid date
}
string formattedDate = dt.ToString("ddMMyyyy");
In one statement it would be:
string formattedDate = DateTime.ParseExact(rawDate.Substring(2),
"ssmmHHddMMyy",
CultureInfo.InvariantCulture)
.ToString("ddMMyyy");
Assuming you update the way dates are stored in the DB all you need is:
DateTime.ParseExact(rawDate.Substring(2), "ssmmHHddMMyyyy", CultureInfo.InvariantCulture).ToString("ddMMyyyy");
Otherwise use the following for the time being:
DateTime.ParseExact(rawDate.Substring(2), "ssmmHHddMMyy", CultureInfo.InvariantCulture).ToString("ddMMyyyy");
In any case you can choose whatever format you wish in the ToString() method.
A regular expression will give you terse code with validation as a bonus:
var match = Regex.Match(rawDate, #"PR\d{6}(?<d>\d\d)(?<m>\d\d)(?<y>\d\d)");
string date = match.Groups["d"].Value + "/" + match.Groups["m"].Value + "/20" + match.Groups["y"].Value;
Related
I have a date in an oracle database, that I query on. This date looks like:
5/3/2016 (after I remove the time portion)
I try to convert this date to a DateTime. I am using:
ParseExact(String, String, IFormatProvider)
I am doing something wrong, which I can't figure out.
My code is shown below. Notice that the variable called "res", has the value 5/3/2016 as described above
try {
while(reader.Read()) {
string res = reader[0].ToString().Substring(0, 8);
mailer.SendSmtpMail4dev("Result: " + res);
mailer.SendSmtpMail4dev("Result: " + DateTime.ParseExact(res, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture));
}
} catch(Exception e) { ...
for DateTime.ParseExact The format of the input string and the format string should be the same, so use:
DateTime.ParseExact(res, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture);
In your case the supplied date is 5/3/2016 and you are specifying that the format is "dd-MM-yyyy" such conversions are not possible. if you need to change the format means you can do like the following:
string res = "5/2/2016";
DateTime givenDate = DateTime.ParseExact(res, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture);
string newFormatedDate = givenDate.ToString("dd-MM-yyyy");
Use:
DateTime.ParseExact(res, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture);
Refer to the MSDN article for details
Use
DateTime.ParseExact(res, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture).ToString("dd-MM-yyyy")
since your res date is dd/MM/yyyy format but you have tried to cast is as dd-MM-yyyy, in DateTime.ParseExact() you have to provide datetime and format string as same format, correct code will be like this
mailer.SendSmtpMail4dev("Result: " + DateTime.ParseExact(res, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture).ToString("dd-MM-yyyy"));
If you have a date why do you convert it to String
// What if server's NLS_* settings are changed? What does 8 stand for?
reader[0].ToString().Substring(0, 8);
and then Parse again? If reader[0] is a date use DateTime:
try {
while(reader.Read()) {
// 0th field is date, then treat it as being date
DateTime date = Convert.ToDateTime(reader[0]);
//TODO: put the right formats here
mailer.SendSmtpMail4dev("Result: " + date.ToString("dd-MM-yyyy"));
mailer.SendSmtpMail4dev("Result: " + date.ToString("dd-MM-yyyy"));
}
}
catch(Exception e) {
...
}
The solution to my problem is marked above, but I just want to state something important, so that others might save some time. Some suggested solutions, suggest doing: DateTime.ParseExact(res, "dd/MM/yyyy" ...) which also seems to be in many other examples on the net, so I'm not saying it's wrong. However. This didn't work for me, I spent some time, before I tried doing:
DateTime.ParseExact(res, "d/M/yyyy" ...)
Notice that in the later solution, there is only one d, and one M.
But my main problem, like everyone pointed out, was probably that I was using:
"dd-MM-yyyy" instead of "dd/MM/yyyy" (which is the same format as the oracle value)
Hope this will save you some time
I need "24/01/2012" but Why it always returns "24/1/2012"
when I am using this
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}", (SessionHelper.SearchFilingStartDate.Value.Day.ToString() + "/" + SessionHelper.SearchFilingStartDate.Value.Month.ToString() + "/" + SessionHelper.SearchFilingStartDate.Value.Year.ToString()));
Just do with this :
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}",SessionHelper.SearchFilingStartDate.Value);
SessionHelper.SearchFilingStartDate.Value seems to be a DateTime value.
Then pass it directly without all that string conversions for day, months and year.
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}",
(SessionHelper.SearchFilingStartDate.Value);
The format string "dd/MM/yyyy" contains enough information to allow the Format method to prepare the resulting string directly from your DateTime value
You don't need the String.Format statement. You can do it with the Date's ToString method:
txtFilingStartDate = SessionHelper.SearchFilingStartDate.ToString.Value("dd/MM/yyyy");
There's a lot more information on the MSDN page for Custom Date and Time Format Strings
You are passing a string and the format you specified for it is unrecognized. Assuming that this is a datetime you are passing, don't do all that conversion first:
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}", SessionHelper.SearchFilingStartDate.Value)
When you format a string using a date/time formatting ({0:dd/MM/yyyy}) themethod is expecting an instance of DateTime, you are passing it a string
You probably want simply:
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}",SessionHelper.SearchFilingStartDate.Value);
I have a simple routine which parses a DateTime.Now & performs a .ToString() on it to add it into a file name to be saved:
DateTime timeNow = DateTime.Now;
string dateNow = timeNow.ToShortDateString();
DateTime dateTime = DateTime.ParseExact(dateNow, "dd/MM/yyyy", CultureInfo.InvariantCulture);
string DateString = dateTime.ToString("dd-MMM-yy");
string fileName = string.Concat("MyArticle_" + region + "_" + DateString + fileExtension);
this is the resulting output string:
MyArticle_Africa_07-May-15.PNG
This is all good until I get a user on an American machine where the DateTime settings are different e.g.
05-07-15
In this case my ParseExact() method throws an exception as the input is not a valid date time. Is there a way to accommodate all date time inputs & parse to dd/MM/YYYY?
Actually, you don't need all these lines of code. You just need this:
// We just have to pass to the ToString
// method the exact format we want. Under the hood the CLR has
// the know how to execute this command and you get the desired
// output.
string DateString = DateTime.Now.ToString("dd-MMM-yy");
Furthermore, we use the DateTime.ParseExact method, when we want to get this exception you have mentioned. Saying this, I mean that we know that the string representation of dates, which we want to parse are of the exact format, we have specified in DateTime.ParseExact and if some of them aren't we wan't to be informed know it. Usually, we would have a try catch clause and in the catch clause we log this.
You need to try this:
string DateString = DateTime.Now.ToString("dd-MMM-yy");
string fileName = String.Concat("MyArticle_" + region + "_" + DateString + fileExtension);
You don't even need to convert DateTime.Now to a string, you can create the entire string in one step using String.Format :
var fileName = String.Format("MyArticle_{0}_{1:dd-MMM-yy}{2}",
region,DateTime.Now,fileExtension);
or
var fileName = String.Format(CurrentInfo.InvariantCulture,
"MyArticle_{0}_{1:dd-MMM-yy}{2}",
region,DateTime.Now,fileExtension);
to avoid internationalization issues.
I have two textBox in first i have Date in this format : 2012.09.20 and in the second i have Time in this format: 15:30:00. In database i have Column name "Eventstart" type: DateTime. Now i like to take the value from two textbox and put them in something like this:
DateTime end = Convert.ToDateTime(TextBoxEnd.Text) + Convert.ToDateTime(TextBoxTimeEnd.Text);
But give me this error : Error 2 Operator '+' cannot be applied to operands of type 'System.DateTime' and 'System.DateTime'
It sounds like you should be using:
DateTime date = Convert.ToDateTime(TextBoxEnd.Text);
DateTime time = Convert.ToDateTime(TextBoxTimeEnd.Text);
DateTime combined = date.Date + time.TimeOfDay;
Or you could combine the text and then parse that:
DateTime dateTime = Convert.ToDateTime(TextBoxEnd.Text + " " +
TextBoxTimeEnd.Text);
I'm not sure I'd use Convert.ToDateTime at all though - if you know the exact format that the textbox will be in, you should use DateTime.TryParseExact. You should work out which culture to use in that case though. If it's a genuinely fixed precise format, CultureInfo.InvariantCulture might be appropriate. If it's a culture-specific format, then use the user's culture.
You might also want to use an alternative UI representation which doesn't use textboxes at all, which would avoid potentially troubling string conversions.
Concatenate your TextBoxes text and use DateTime.ParseExact with format "yyyy.MM.dd HH:mm:ss"
After concatenating the text you should have: "2012.09.20 15:30:00"
DateTime dt = DateTime.ParseExact(TextBoxEnd.Text + " " + TextBoxTimeEnd.Text,
"yyyy.MM.dd HH:mm:ss",
CultureInfo.InvariantCulture);
Have you tried something like
DateTime end = Convert.ToDateTime(TextBoxEnd.Text) + TimeSpan.Parse(TextBoxTimeEnd.Text);
First concatenate both the values and then add it to a DateTime variable
example:
string str = date.Text + time.Text; // assumed date and time are textboxes
DateTime dt=new DateTime();
DateTime.TryParse(str,dt); // returns datetime in dt if it is valid
How to convert C# Datetime.Today, into Timestamp format 10/20/2011 12:00:00 in mysql?
If you want to get the date time as a string in that format then you can do...
string dt = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
See here for extra formatting options for the DateTime ToString method
Though from my understanding of MySQL it will accept a timestamp in the format yyyy-MM-dd HH:mm:ss. I would recommend doing this as it will ensure dates like 05/08/2011 are parsed correctly for the right month and day...
string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
Try this:
DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
and if you want more/other time formats, check this.
You can use something like following and use return value as timestamp for Sql.
public static string GiveMeTimestamp(DateTime value)
{
return value.ToString("yyyy/MM/dd HH:mm:ss:ffff");
}
Use the overloaded ToString method which takes a string argument for the format.
This Possibly may assist someone with the same approach and thought that I had:
To test directly in MYSQL Workbench:
INSERT into tblDemo VALUES (898,CURRENT_TIMESTAMP());
create table tblDemo (ScenarioID INT(10),
ProcessTime DATETIME DEFAULT CURRENT_TIMESTAMP() NOT NUll);
Now compile the string in your C# Code like so:
string query = "INSERT into tblDemo " +
"VALUES (" + ScenarioID + "," + " CURRENT_TIMESTAMP())";
Note the CURRENT_TIMESTAMP() in quotes in the above query
Output:
'2021-03-04 17:52:30'