I am exporting date values("24/11/2016") from excel file to SQL database table in C#.NET. I am using the following code into my function to parse the date values from string to Datetime. But it is not working. I tried to debug it but when it comes on that line, it's terminating. Anybody know what is the problem.
var date = row["Date"].ToString();
DateTime dates;
string format = "MM-dd-yyyy";
if (!DateTime.TryParseExact(date, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dates))
{
continue;
}
else
{
dates = DateTime.Parse(date); //terminating at this line
}
Your format should be dd-MM-yyyy as you have 24/11/2016 as date, you can learn more about string formats in this MSDN article Custom Date and Time Format Strings
Change
string format = "MM-dd-yyyy";
To
string format = "dd-MM-yyyy";
Edit based on comments by OP - Storing formatted date in SQL server
The DateTime is stored in a SQL server in standard format that is not in fact the presentation format we see like "dd-MM-yyy". This article Solving the Datetime Mystery explains the internal SQL server format.
Excerpt from Solving the Datetime Mystery
So how does SQL Server internally store the dates? It uses 8 bytes to
store a datetime value—the first 4 for the date and the second 4 for
the time. SQL Server can interpret both sets of 4 bytes as integers.
For the date portion, the value SQL Server stores is the number of
days before or after a base date of January 1, 1900. Because of this
storage protocol, SQL Server assumed the date of January 1, 1900, when
I didn't supply the date in my first example. SQL Server internally
stored a value of 0. A negative number represents a date earlier than
January 1, 1900.
SQL Server stores the second integer for the time as the number of
clock ticks after midnight. A second contains 300 ticks, so a tick
equals 3.3 milliseconds (ms). You can see the values for days and
clock ticks by converting a datetime value to a binary(8) value and
using the substring function to extract each set of 4 bytes. The code
in Figure 3 then converts each set of 4 bytes into an integer.
Finally i did it using the following code:
string format = "dd/MM/yy";
if (!DateTime.TryParseExact(date, format, CultureInfo.InvariantCulture, DateTimeStyles.None,out dates))
{ continue; }
else
{ dates = DateTime.ParseExact(date, format, CultureInfo.InvariantCulture); }
String datetime = dates.ToString("yyyy-MM-dd");
Thanks to all.
Related
I am working on a program that gets a list of file names from a directory, then parses the file names into individual variables (strings) and converts it into something that can be submitted to a mysql database that will the later be queued for searches.
In those file names contain a 4 digit year, 2 digit day, 2 digit month, 2 digit hour, and 4 digit minute (##AM/PM), followed by 2 numbers that can be between 3 and 11 digits.
I have parsed the filename and formatted the date and time info into the following string: YYYY/DD/MM HH:MMAM or YYYY/DD/MM HH:MMPM (only "AM" and "PM" changes on minutes).
EX: 2014/24/12 02:50PM
How can I convert the string into DateTime to submit into a MySql database.
The built-in STR_TO_DATE() function does what you need.
STR_TO_DATE('2014/24/12 02:50PM', '%Y/%d/%m %h:%i%p')
gives the result you need. You can look up the format codes here.
Using DateTime.ParseExact will do the trick to get it into .net's DateTime object:
string s = "2014/24/12 02:50PM";
DateTime dt;
DateTime.TryParseExact(s, "yyyy/dd/MM hh:mmtt", new CultureInfo("en-US"), DateTimeStyles.None, out dt) ;
Console.WriteLine(dt.ToString());
Currently, I have a datetime field in one of my sqlserver table.
And I Query (SELECT Column1, myDateField FROM MyTimeTable BETWEEN #startDate AND #endDate).
NOW I got Column1, myDateField at C# code side using Entity framework.
Problem
Then I'm passing these dates to client side as json. Now, asp.net converts date to "\/Date(1410588000000)\/" format. (ie date '19-9-2014' to 1410588000000). When I create date with this ticks (From 1970 ticks of javascript) it will add extra 5.00 hours (server timezone is -5.00). This happens because while converting datetime to "\/Date(xxxxxxxxx)\/" format, .net consider the date in database (ie, now a c# datetime using entity framework) is local (-5.00). So it creates ticks for +5.00 hours. How can I convince .net that the time is in utc?
Please convert your DATE TIME to any fixed specific format and than follow it every where,
So it will help you to maintain the consistency.
Write query like below
SELECT CONVERT(VARCHAR(30),GETDATE(),113) AS DateConvert;
Format will be "dd MMM yyyy hh:mm:ss:zzz"
this will send exact date time format , which will be converted easily.
Hope this will help you.
Now we can use DateTime.ParseExact to convert received string (Date) to DateTime
C# code
String dateString = "01 Jun 2008 08:30:06:00";
CultureInfo provider = CultureInfo.InvariantCulture;
String format = "dd MMM yyyy hh:mm:ss:zzz";
try {
DateTime result = DateTime.ParseExact(dateString, format, provider);
}
Thanks
Var date = new Date();
now the date have the value of client's time.
alert(new Date());
I am trying to build a nice, small database to run on a mobile application (Windows Mobile 5, if you are curious).
In the SQLite Documentation, the Date and Time Datatype is defined as follows:
1.2 Date and Time Datatype
SQLite does not have a storage class set aside for storing dates
and/or times. Instead, the built-in Date And Time Functions of SQLite
are capable of storing dates and times as TEXT, REAL, or INTEGER
values:
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic
Gregorian calendar.
INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
Applications can chose to store dates and times in any of these
formats and freely convert between formats using the built-in date and
time functions.
So, saving my DateTime value as either a REAL (float) or INTEGER is the same size.
What about the TEXT format? There are 23 characters above in the text YYYY-MM-DD HH:MM:SS.SSS. Is that 8-bytes per character? If so, that is a HUGE waste of space to store in Text format (which is what I am currently doing).
What about the REAL format? Would I define a base date of November 24, 4714 B.C.? (I am not even sure if Visual Studio 2008 will let me do that. I've never tried.) Then get the TimeSpan between base date and date I want, extract the number of days, and store that?
// is this how to declare this date?
private static readonly DateTime nov24_4714bc = new DateTime(-4714, 11, 24);
public static double GetRealDate(DateTime dateTime) {
// FYI: subtracting dates in .NET returns a time span object
return (dateTime - nov24_4714bc).TotalDays;
}
What about the INTEGER format? Would I define a base date of 1970-01-01 00:00:00 UTC (please tell me how to do that!), then get the TimeSpan between base date and my input date, extract the number of seconds, and store that?
// is this a UTC date?
private static readonly DateTime utc1970_01_01 = new DateTime(1970, 1, 1);
public static double GetIntDate(DateTime dateTime) {
// FYI: subtracting dates in .NET returns a time span object
return (dateTime - nov24_4714bc).TotalSeconds;
}
Any help with this? I am a little confused on a few points.
Use the TEXT format if "human-readability" is important.
Use one of the numeric formats if saving space is important.
If you don't need millisecond precision, you can save space in the TEXT format by only including the part you do need. There are 3 shorter formats accepted by SQLite date/time functions:
YYYY-MM-DD HH:MM:SS (19 characters)
YYYY-MM-DD HH:MM (16 characters)
YYYY-MM-DD (10 characters)
(NEVER use MM/DD/YYYY; it's not supported, and it doesn't sort correctly.)
Would I define a base date of November 24, 4714 B.C.? (I am not even
sure if Visual Studio 2008 will let me do that. I've never tried.)
You can't: System.DateTime only supports the years 1 to 9999. You need to pick a different base date, and then do (dateTime - baseDate).TotalDays + baseDateJD, where baseDateJD is the Julian date of the base date. Some reasonable choices are:
0001-01-01 = JD 1721425.5
1970-01-01 = JD 2440587.5
2000-01-01 = JD 2451544.5
I have result string date xml export from database like "2011-06-27T14:03:19.5300000+07:00". How to Convert to format datetime fully(date and time) in C# or VB.Net language datetime?
Please help me
Thanks in Advance
You can use DateTime.Parse
The DateTime.Parse(String) method
tries to convert the string
representation of a date and time
value to its DateTime equivalent. The
string to be parsed can take any of
the following forms:
A string with a date and a time
component.
A string with a date but no time
component.
A string with a time but no date
component.
A string that includes time zone
information and conforms to ISO 8601.
For example, the first of the
following two strings designates the
Coordinated Universal Time (UTC); the
second designates the time in a time
zone seven hours earlier than UTC:
2008-11-01T19:35:00.0000000Z
2008-11-01T19:35:00.0000000-07:00
A string that includes the GMT
designator and conforms to the RFC
1123 time format. For example:
Sat, 01 Nov 2008 19:35:00 GMT
A string that includes the date and
time along with time zone offset
information. For example:
03/01/2009 05:42:00 -5:00
DateTime dt = DateTime.Parse("2011-06-27T14:03:19.5300000+07:00");
The main point is to use DateTime.TryParse
string rawDate = "2011-06-27T14:03:19.5300000+07:00";
DateTime dt = DateTime.MinValue;
if (!DateTime.TryParse(rawDate, out dt))
{
Debug.WriteLine("Unable to parse");
}
If you're using XDocument you can simply call conversion operator to DateTime.
I was searching here about converting a string like "16:20" to a DateTime type without losing the format, I said I dont want to add dd/MM/yyy or seconds or AM/PM, because db just accept this format.
I tried with Cultures yet
Thanks in Advance
Just give a date format to your dateTime.
string DateFormat = "yyyy MM d " this willl give you the year month and day. after continuing;
string DateFormat = "yyyy MM d HH:mm:ss " in here the Capital H will give you the 24 hours time format and lowerCase "h" will give you the 12 hours time format...
when you give the Dateformat as a string you can do whatever you want with date and time.
string DateFormat = "yyyyMMdHHmmss";
string date = DateTime.Now.ToStrign(DateFormat);
OR
Console.writeline(DateTime.Now.ToStrign(DateFormat));
OUTPUT:
20120823132544
All DateTime objects must have a date and a time.
If you want just the time, use TimeSpan:
TimeSpan span = TimeSpan.Parse("16:20");
If you want a DateTime, add that time to the min value:
TimeSpan span = TimeSpan.Parse("16.20");
DateTime dt = DateTime.MinValue.Add(span);
// will get you 1/1/1900 4:20 PM which can be formatted with .ToString("HH:mm") for 24 hour formatting
DateTime.Now.ToString("hh:mm") - If it's C#.
Oh. Only read the header.
DateTime dt = new DateTime(2008, 12, 11, Convert.ToInt32("16"), Convert.ToInt32("32"), 0);
what do you mean by "losing the format".
if you convert it to a DateTime type, then the DateTime object will have dd/mm/yy and other properties. depending on how you plan to use the object, you can "recover" your original settings, by formatting the string output like this: DT.ToString("HH:mm");
Since you don't stipulate which DBMS you are using, it is hard to know which answer will help you. If you use IBM Informix Dynamic Server, you would simply use the data type 'DATETIME HOUR TO MINUTE', which will record values in the 24 hour clock.
DateTime.Parse("16:20")
I want to address this part of your question:
without losing the format
A database will generally store all datetime values in a standard common format that's not even human readable. If you use a datetime column the original format is destroyed.
However, when you retrieve the value you cast it back to any format you want. If you want HH:mm you can get it.