In a part of my system, I have this situation: I will receive a string that represents a date and another string that represents a time.
I need to let these informations in DateTime. So, a made it:
string date = "17012012";
string hour = "103445";
date = string.Format("{0}/{1}/{2}", date.Substring(0, 2),
date.Substring(2, 2), date.Substring(4, 4));
hour = string.Format("{0}:{1}:{2}", hour.Substring(0, 2),
hour.Substring(2, 2), hour.Substring(4, 2));
DateTime example = new DateTime();
example = DateTime.Parse(string.Format("{0} {1}", date, hour));
Ok, but is it a good pattern? Are there a "more beautiful" way to do this?
You could use DateTime.ParseExact instead
e.g.
DateTime.ParseExact(date + hour, "ddMMyyyyHHmmss", CultureInfo.InvariantCulture);
Take a look at the Parse and ParseExact DateTime methods in the MSDN documentation.
I think that also Parsing Dates and Times in .NET can help.
One way or another your program must parse this format.
I would have done like this:
string date = "17012012";
string time = "103445";
int year = Convert.ToInt32(date.Substring(4, 4));
int month = Convert.ToInt32(date.Substring(2, 2));
int day = Convert.ToInt32(date.Substring(0, 2));
int hour = Convert.ToInt32(time.Substring(0, 2));
int minute = Convert.ToInt32(time.Substring(2, 2));
int second = Convert.ToInt32(time.Substring(4, 2));
DateTime example = new DateTime(year, month, day, hour, minute, second);
Related
I am trying to create a DateTime object, but it seems to be giving me an error.
int month = "1"
int year = "2017"
DateTime date = new DateTime(year, month, DateTime.Day);
It doesn't seem to like DateTime.Day. It says an object reference is required for the non-static field.
How could I get today's day(16th) as a parameter? Also, I need the date to have hh:mm:sss... how could I do that?
Thanks for your help!
Use
var day = DateTime.Now.Day;
for today.
You can add hh:mm:sss to the date object in the constructor too:
DateTime date = new DateTime(year, month, DateTime.Now.Day, 10, 11, 12);
10 => hours
11 => minutes
12 => seconds
Of course you can use DateTime.Now.Hour etc. for the current values.
An ArgumentOutOfRangeException is thrown if the values are not valid for a real date, e.g. 30.2.xxxx.
You can print the date object in different formats, read the MS Documentation for all possibilities.
It should be:
int month = 1;
int year = 2017;
DateTime date = new DateTime(year, month, DateTime.Now.Day);
Take note, you declare integer without quotation marks:
int month = 1;
To convert it on 24 hour format with milliseconds as requested on comment:
string strResult = string.Format("{0:MM/dd/yyyy HH:mm:ss.fff}", date);
//Results: 02/17/2017 00:00:00.000
For 12 hour:
string strResult = string.Format("{0:MM/dd/yyyy hh:mm:ss.fff}", date);
//Results: 02/17/2017 12:00:00.000
Why I can apply that code to other form .cs
string dt = day + "/" + month + "/" + year;
DateTime newDate = DateTime.ParseExact(dt, "dd/MM/yyyy", null);
It always show error this
String was not recognized as a valid DateTime.
It have to change like this
"dd/MM/yyyy" --> "d/M/yyyy"
But in other form .cs, that code works. Don't need to change that string
By specifying dd and MM you require the input to be 2 characters wide.Your code will work for 10/10/2015, but not for 1/1/2015.
Change your code to allow single day and month characters and you will be fine:
DateTime newDate = DateTime.ParseExact(dt, "d/M/yyyy", null);
I think your variables day and month does not contain leading 0 and that's why your parsing is not working. Here are some references to the MSDN page were you can find out more about ParseExact and Time formats
if you know date parts, there is a simple way to construct DateTime:
from ints:
int day = 1;
int month = 1;
int year = 2015;
DateTime newDt = new DateTime(year, month, day);
Console.WriteLine(newDt);
from strings:
string sday = "1";
string smonth = "1";
string syear = "2015";
DateTime newDts = new DateTime(int.Parse(syear), int.Parse(smonth), int.Parse(sday));
Console.WriteLine(newDts);
demo
dd/MM/yyyy requires two digits for the day and month, as in 10/09/YYYY; whereas d/M/yyyy accepts one or digits!
Read about the format codes on MSDN.
The code dt = day + "/" + month + "/" + year will not add leading zeroes to day and month.
I suggest using a DateTime constructor, as in
DateTime newDate = DateTime(year, month, day);
Then you will not have any issues with string formats.
Hi I have julian date string YYJJJ format. eg 05365(31st dec 2005). I want to covert to MMDDYY format(123105).
Is there any defined function for that in?
I faced same problem as I was try to convert dates from BACS 18 standard to a String. I couldn't find ready solution to this problem so I wrote this function:
private String bacsDateConvert(String bacsFormatDate)
{
int dateYear = Convert.ToInt16(bacsFormatDate.Substring(1, 2));
int dateDays = Convert.ToInt16(bacsFormatDate.Substring(3, 3));
DateTime outputDate = new DateTime();
outputDate = Convert.ToDateTime("31-12-1999");
outputDate = outputDate.AddYears(dateYear);
outputDate = outputDate.AddDays(dateDays);
String outputString = outputDate.ToString("yyyyMMdd");
return outputString;
}
//You may call it like this:
textBox4.Text = Convert.ToString(bacsDateConvert(bacsTxnValueDate));
You also may modify it slightly and easily make it return DateTime data type if you want to. I just needed to return a string in the above format.
First of all, there is no YY, JJJ and DD formats as a custom date and time format. One solution might be to split your string Year and DayOfYear part and create a DateTime with JulianCalendar class.
string s = "05365";
int year = Convert.ToInt32(s.Substring(0, 2));
// Get year part from your string
int dayofyear = Convert.ToInt32(s.Substring(2));
// Get day of years part from your string
DateTime dt = new DateTime(1999 + year, 12, 18, new JulianCalendar());
// Initialize a new DateTime one day before year value.
// Added 1999 to year part because it makes 5 AD as a year if we don't.
// In our case, it is 2004/12/31
dt = dt.AddDays(dayofyear);
// Since we have a last day of one year before, we can add dayofyear to get exact date
I initialized this new DateTime(.. part with 18th December because
From Julian Calendar
Consequently, the Julian calendar is currently 13 days behind the
Gregorian calendar; for instance, 1 January in the Julian calendar is
14 January in the Gregorian.
And you can format your dt like;
dt.ToString("MMddyy", CultureInfo.InvariantCulture) //123105
I honestly didn't like this way but this is the only one I can imagine as a solution.
I have strings likes this:
' 630AM' , '1234PM' , '1000 '
These are the values saved in my Database.
And I want to parse them to a date time format, the Date part I don't care, can append a dummy date.
One way is to just have a bunch of if-else and string processing commands to solve it but I feel like we should some how be able to use DateTime.TryParseExact and do it in a cleaner way.
What do you suggest to be done along those lines?
This is how I would handle these:
public DateTime convert(string date)
{
int hour = int.Parse(date.Substring(0, 2));
int minute = int.Parse(date.Substring(2, 2));
if (hour < 12 && date.Substring(4, 2) == "PM")
{
hour = hour + 12;
}
return new DateTime(2014, 1, 10, hour, minute, 0);
}
I am comparing the time now to a time stored somewhere in a database. The time stored in the database is in the format of "yyyyMMddHHmmss". For example, the database may return 201106203354 for a stored time value. I am then using a function to compare the time now to the time read in from the database.
What I am doing now:
Create 6 int variables
Take the sub-string from the formatted date string and convert the sub-string to an int32.
Pass the 6 int variables to the function.
What I would like to do:
Rather than splitting up the formatted date-time string, and seperately creating and assigning six variables to pass to the function, I would like to know if there is some way to simply convert the formatted date-time string into DateTime.
Please see my code as it will help to explain what I clearly cannot ...
Pass time now along with time read from database:
Private void passTime()
{
string timeStamp;
int year, month, day, hour, minutes, seconds;
DateTime dt = DateTime.Now;
timeStamp = dt.ToString("yyyyMMddHHmmss");
year = Convert.ToInt32(timeStamp.Substring(0, 4));
month = Convert.ToInt32(timeStamp.Substring(4, 2));
day = Convert.ToInt32(timeStamp.Substring(6, 2));
hour = Convert.ToInt32(timeStamp.Substring(8, 2));
minutes = Convert.ToInt32(timeStamp.Substring(10, 2));
seconds = Convert.ToInt32(timeStamp.Substring(12, 2));
MessageBox.Show(GetDifferenceDate(
new DateTime(year,month,day,hour,minutes,seconds),
// Example time from database
new DateTime(2011, 08, 11, 11, 40, 26)));
}
static string GetDifferenceDate(DateTime date1, DateTime date2)
{
if (DateTime.Compare(date1, date2) >= 0)
{
TimeSpan ts = date1.Subtract(date2);
return string.Format("{0} days",
ts.Days);
}
else
return "Not valid";
}
So, quite simply, I would like to compare two dates that are both in the format of "yyyyMMddHHmmss", or if this is not possible, I would like to convert the previous Date string into a DateTime.
I'm sure I left something out here, I will go back and read it again but please feel free to ask me anything that I left unclear.
Thank you,
Evan
You're looking for ParseExact:
DateTime.ParseExact(timeStamp, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)