how to add current date time in bigint field - c#

I need to add the current date time in a bigint field in a database... and then display from that only the date in format: october 1, 2009.
I am currently thinking of storing the value in string variable and then converting it to int...
String s = DateTime.Now.ToString();
i dont know what to do next..
please help

You could just store the number of ticks as your bigint value. Ticks represent the number of elapsed 1/10,000 of milliseconds since January 1, 0001.
DateTime.Now.Ticks;
This can always be converted back to a DateTime by using the constructor that accepts a long:
DateTime storedTime = new DateTime(ticksFromDatabase);
To format your date, just use any of the standard date format strings. A custom format string might work better actually, I just perused them and it doesn't look like there's a built in one for the format you want. This should work:
date1.ToString("MMMM d, yyyy", CultureInfo.CreateSpecificCulture("en-US"))

I'd use a smart date key, since it's easier to find that using SQL:
20090927235000
yyyyMMddhhmmss
This way, if you want to find anything that happened on a given day, you could do:
select * from tbl where datecol between 20090927000000 and 20090927240000
Thereby making data validation a lot easier, even if you are using an ORM.

Related

Wrong datetime in sqlite expert personal

I'm trying to write to my sqlite db from visual studio in c#. When using datetime. Now in visual studio it shows me the correct date and time but when writing to the db it shows something like 1899/30/12. Why is that? Here is my code:
SQLiteCommand cmd = new SQLiteCommand("INSERT INTO tblLicenseInfo (ID, UserID, MachineID, ExpirationDate, DateOfChange, LicenseKey)
VALUES(1, 1, 1, #test, #test, 'sdfsafge45345345');", SqLite);
cmd.Parameters.Add("#test", DateTime.Now);
SqLite.Open();
cmd.ExecuteNonQuery();
SqLite.Close();
Thanks for your help.
DateTime.Now is in the incorrect format, so you have 2 options:
Use CURRENT_TIMESTAMP as value. This is a SQLite keyword.
Or
Format Datetime: DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
I'm not quite sure why SQLiteParameterCollection.Add(String,Object) method overload doesn't work because it says:
Adds a SQLiteParameter to the SQLiteParameterCollection given the
parameter name and value.
As an alternative, you can use other overloads or AddWithValue as well like;
cmd.Parameters.Add("#test", SQLiteType.DateTime).Value = DateTime.Now;
or
cmd.Parameters.AddWithValue("#test", DateTime.Now);
More informations;
Using Parameters
But wait a second.. You said your column type is DATETIME but there is no data type like that in SQLite.
From Datatypes In SQLite Version 3
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.
Please tell the real type of your columns. I assume DateTime.Now doesn't fit these 3 type formats (or values) and that's why you get 1899/30/12 used as a "default" date in SQLite.
From Date And Time Functions
The date and time functions use a subset of IS0-8601 date and time
formats. The date() function returns the date in this format:
YYYY-MM-DD.
I feel like if you make your column type as TEXT and if you send your DateTime.Now with YYYY-MM-dd format, your code should work;
cmd.Parameters.Add("#test", SQLiteType.TEXT).Value = DateTime.Now.ToString("YYYY-MM-dd");

want 24 hr format time in DateTime in C#

My date and time are stored in database in 24 hr format.What i do is use a stored procedure to fetch the required date and times and insert in a datatable. But in the datatable it automatically converts in 12 hr format.After fetching data from datatable it is possible to convert it into 24hr pattern but it has to be converted into string.But the problem is that i need to use the data to create a chart which would only accept DateTime format.
So what i want is some way to convert 12 hr time to 24 hr time format without changing it to string.Please help.
My date and time are stored in database in 24 hr format.
I hope they're not actually stored in any text format, but instead in a DateTime field or something similar. Don't confuse "what I see when I run a SQL query" with "what's stored in the database." Just as numbers aren't stored as sequences of decimal digits, dates and times shouldn't be stored as text.
But in the datatable it automatically converts in 12 hr format.
No, if you've done everything properly it should be storing everything in the DataTable as a DateTime. In the debugger you may see a 12-hour string representation, but the object itself should be a DateTime.
Basically the 12/24-hour problem is only a symptom of the real problem: unnecessary string conversions. Track those down (and remove them), and the rest should take care of itself. So if yo're currently calling ToString() when you extract the value from the DataTable, stop doing that. Instead, just cast:
DateTime dateTime = (DateTime) row["foo"];
From your story, I understand that the DataTable actually contains a DateTime value, which doesn't have any format by itself, it basically just stores a number of ticks since an arbitrary date and time. What you are seeing in your table visualization is the default ToString() conversion, based on your application's culture settings.
Most likely, if you were to do something like this before running your existing code, the format would change:
var cultureInfo = new CultureInfo(CultureInfo.CurrentCulture.Name);
cultureInfo.DateTimeFormat.LongTimePattern = "HH:mm:ss";
Thread.CurrentThread.CurrentCulture = cultureInfo;
I would recommend converting to a format of your preference by calling ToString explictly however. How exactly you would best accomplish this depends on how you are visualizing the data from the DataTable.
All that #Jon said is right.
But if you just explained yourself wrong, and you do have DateTime object in your db, and you are looking to format it into 24 hr only when displaying - you can use "HH" in string format for 24 hour format.
For example, for myDateTime representing 16:00:
var hourPart = String.Format("{0:HH}", myDateTime)
Console.WriteLine(hourPart); // prints 16, and not 4PM.

Store and Retrieve DateTime to SQL as Integer

I've played a little with SQLite in the past, and I like it enough that I want to use it for a new project.
Step 1 is creating the database, and I need to create a DateStamp field where I place a time stamp on when an event occurred.
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.
I'd rather not save dates as text, and since the Windows DateTime object does not go back to November 24, 4714 B.C., I supposed I'm left with storing DateTime values as an INTEGER.
So, how do I store the DateTime as an Integer? Would I get the TimeSpan between base date and date I want, extract the number of days, 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;
}
Is that right? Is this what everyone else is doing that uses SQLite?
It also says that SQLite stores datetime in UTC time, so I need to convert again on top of that.
Surely someone has done this before. I would appreciate seeing tools someone has made already that handles these inputs. SQLite has some built in functions, but I don't really understand how to use them.
Solved:
Well poo.
Could it be as simple as this?
public static long ToFileTimeUtc(DateTime dateTime) {
return dateTime.ToFileTimeUtc();
}
public static DateTime FromFileTimeUtc(long fileTimeUtc) {
return DateTime.FromFileTimeUtc(fileTimeUtc);
}
Comments?
Can I not do that?
Whether or not you can use FileTime depends on whether anything but your app will ever be accessing the data. FileTime represents the number of 100-nanosecond intervals since January 1, 1601 (UTC).
As such, you will need to make sure the integer is an 8 byte integer in SQLLite in order to store the entire value.
As long as your app is the only app to deal with this data, and you always use FileTime, then there's no problem. If others will access this data, and they're capable of understanding FileTime, and they are aware that this is what it is, then there is also no problem.
Well poo.
Could it be as simple as this?
public static long ToFileTimeUtc(DateTime dateTime) {
return dateTime.ToFileTimeUtc();
}
public static DateTime FromFileTimeUtc(long fileTimeUtc) {
return DateTime.FromFileTimeUtc(fileTimeUtc);
}
Comments?
Can I not do that?

How I can convert DateTime.now in C# to yyyy-mm-dd hh:mm:ss.sssssss?

I'm storing in my database using a store procedure the date time stamp using a function called sysdatetime() and a type of varchar(max) which stores in the database in this format yyyy-mm-dd hh:mm:ss.sssssss. When I'm creating a new post its fine but when I'm trying to update the record I have to send a parameter to the store procedure with the current datetime. I have tried this one
DateTime.Now.ToString(yyyy-mm-dd hh:mm:ss.sssssss)
but I'm getting an error. what i have to do?
P.s: see the image below with the error message
I suspect if you really need the string representation, you actually want:
string text = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fffffff",
CultureInfo.InvariantCulture)
Note that:
Unless you really want the local time, use UtcNow instead of Now. For timestamps, you almost always want UTC.
I doubt that you want to use the time separator of the current culture, hence the specification of CultureInfo.InvariantCulture
"MM" means months whereas "mm" means minutes
"HH" means 24-hour clock whereas "hh" means 12-hour clock
"ff..." is used for fractions of a second
See MSDN for more details of custom date and time formatting.
However, I'd strongly recommend that you try to avoid string conversions wherever possible. Why can't your stored procedure just use the relevant DateTime type instead of a string representation? Then you can pass the value to the stored procedure as a DateTime (via a command parameter) and you can get rid of the error-prone string conversion clutter.
Use this code:
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffffff")
See this ref: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Here a small sample:
DateTime date3 = new DateTime(2008, 1, 1, 0, 30, 45, 125);
Console.WriteLine("Date with milliseconds: {0:MM/dd/yyy hh:mm:ss.fff}",
date3);
// Displays the following output to the console:
// Date with milliseconds: 01/01/2008 12:30:45.125
Just put the appropriate number of "f"s into your command and you are done

Incomplete DateTime In C#

In C# if I want to parse a datetime, but some times I just have either a date and not a time component or no date but a time component, how would I do this? Usually when you leave out the time component, it automatically assumes that the time is 12:00AM. But I don't want this. If the time component is missing then I just want the DateTime to store a date only and the leave the time component off.
The value of a DateTime internally is just an UInt64 (ulong in C#) that stores the number of ticks since some date in the past, so whether you like it or not, the time component will always be there.
If you only need to display certain parts, just use any of the format strings (examples are for "en-us" culture):
DateTime.Now.ToString("d"); // 5/26/2009
DateTime.Now.ToString("t"); // 4:56 PM
The complete reference: http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
It's not possible to have a DateTime without a time component. You could store a boolean flag along with it in a struct to store data about existence of that component. However, there's no way to use the automatic parsing routine to distinguish between a DateTime string with a time specified as 12:00 PM and a nonexistent one.
If it really bugs you you can always create a wrapper class that can hide the time portions of the datetime class.
No you will have the time component no matter what. The best you can do is access the Date property on your DateTime object if you really have to.
http://msdn.microsoft.com/en-us/library/system.datetime.date.aspx
DateTime by definition stores a date and a time such that it cannot just represent one of them without representing the other. If you only want the date (or only the time), parse out the information you need and discard the rest of it.
As mentioned before DateTime will always have a Date and a Time part of it if you only want a single part use the way described by the others
DateTime date = DateTime.Parse("2009-11-30);
date.Year; = 2009
date.Month; = 11
date.Day; = 30
date.Hour; = 0
and so on
The thing you must be aware is that all of these methods will only return an integer.
If you want to know all the possible ways to parse a string John Sheehan has put together a great Cheat Sheet wit all possible ways to parse and manipulate dates, and other strings for that matter.
You could have a class that stores a DateTime and determines if the time was ever set or if just the date was set and return values accordingly.
Use
DateTime date = new DateTime();
date = DateTime.Parse("1/1/2001");
to set the date, then use
date.ToShortDateString();
or
date.Year;
date.Month;
date.Day;
to get what you need. Hope that helps!
A DateTime object is always stores a date + a time, not just one. You can always choose to work only with the date part, i.e. only use properties like Year, Month, DayOfWeek. But underneath there will aways be some stored time.
It is very dangerous to assume that the date portion of a DateTime is necessarily the date you are expecting. As pointed-out, DateTime always includes and considers the time aspect, even when you don't see it.
This is a big problem when you have data stored in different time-zones (and particularly if knowledge of that offset is not also kept, because it is assumed that what is being stored is a Date, not a date-with-time).
You may store a birthdate as '01/01/2000 00:00:00' during Summer-Time, which then is stored in UCT as '31/12/1999 23:00:00'. When you then read that birth-date later, the date portion is now a day early.
Best to create your own type. Strange that Microsoft didn't think it worth having a Date type.

Categories