I am trying to convert a DateTime variable to Timestamp. My variable has the current format : 1/23/17 2:14:31 PM and I would like it to be TimeStamp like so I can use it for Oracle SQL Developer. eg: 23-JAN-17 2.14.31.000000000 PM.
I have tried to convert it like this:
DateTime d = DateTime.Now.AddDays(-31);
Console.WriteLine(d.ToUniversalTime().ToString("O"));
but the output is nothing like TimeStamp:
2017-01-23T14:14:31.5838355Z
Try this:
DateTime d = DateTime.Now.AddDays(-31);
long epoch = (d.Ticks - 621355968000000000) / 10000000;
Console.WriteLine(d.ToUniversalTime().ToString("dd-MMM-yy HH:mm:ss") + ":" + epoch);
Try this one
DateTime d = DateTime.Now.AddDays(-31);
Console.WriteLine(d.ToUniversalTime().ToString("hh-MMM-yy hh.mm.ss.ffffff tt"));
Related
I have a JS function that generates today date:
function GetDate(date) {
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0');
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
alert(today);
return today; // 13/03/2021
}
This function returns 13/03/2021
I pass it on to Server Side Code and do this :
DateTime dateToday = DateTime.ParseExact(cdate, "dd/MM/yyyy", CultureInfo.GetCultureInfo("en-AU"));
emailCopy = emailCopy.Replace("{date}", dateToday.ToString("dd MMMM yyyy"));
However here it puts the date as 12 March 2021
Why is it doing that? The date going in is clearly 13/03/2021. Also in next line I pass this date to be added to SQL Server Table:
dateToday.ToString("yyyy-MM-dd")
And the date added to the database is also correct : 2021-03-13.
When you create a new DateTime object, but only set the date part of it, this sets the time to 00:00:00 (midnight). This is in GMT. So when you format the date it takes the date you set at midnight, and converts it to your time zone, which is actually the day before.
You can fix this by doing this "kludge":
var now = DateTime.Now;
var adjusted = new DateTime(
dateToday.Year, dateToday.Month, dateToday.Day, now.Hour, now.Minute, now.Second);
var final = adjusted.ToString("dd MMMM yyyy");
There may be a better way to do this, though.
ETA
You should consider using JavaScript's Date.toISOString() instead of just sending the date. Then in C#, use Convert.ToDateTime() to parse it. That uses UTC and you are guaranteed to get the exact time that the client machine generated the date.
I have a DataGrid which contains a few values that are in hours and I wanted to know:
How to get ONLY the time from my DataGrid and convert it into an int (or double) variable.
My goal is to do a few operations with my DataGrid time values, like to add numbers into it
EXAMPLE:
Using my "dataGridView1.Rows[1].Cells[2].Value.ToString();" It'll show a DateTime value (which is inside my DataGrid), with this value, I wanna filter ONLY the time from this and convert it into an int
the part of my code which I wanna "capture" the time:
txtAtiv.Text = dataGridView1.Rows[0].Cells[1].Value.ToString();
string value = dataGridView1.Rows[0].Cells[2].Value.ToString();
lblLeft.Text = value.Split(' ')[1];
I wanna get the "value" (which is a DateTime value from the DataGrid) and convert it into an int.
note:
- The date for me in my dataGrid it's not relevant, I only have to pick the time (and yes, I know that I can't "split" DateTime to do them separately)
If you are willing to be limited to millisecond resolution, then this is fairly easy.
Given a date/time that you want to get the time part from as an int, you can get the number of milliseconds since midnight, like so:
DateTime dateTime = DateTime.Now;
int timeMsSinceMidnight = (int)dateTime.TimeOfDay.TotalMilliseconds;
If you want to reconstitute the original date and time from this, you need the original date and the time since midnight in milliseconds:
DateTime date = dateTime.Date; // Midnight.
DateTime restoredTime = date.AddMilliseconds(timeMsSinceMidnight);
Test program:
DateTime dateTime = DateTime.Now;
Console.WriteLine("Original date/time: " + dateTime );
int timeMsSinceMidnight = (int)dateTime.TimeOfDay.TotalMilliseconds;
DateTime date = dateTime.Date; // Midnight.
DateTime restoredTime = date.AddMilliseconds(timeMsSinceMidnight);
Console.WriteLine("Restored date/time: " + restoredTime);
The value returned from time.TimeOfDay is of type TimeSpan, which is convenient for storing time-of-day values.
If you want to turn your "milliseconds since midnight" back into a TimeSpan, you just do this:
var timeSpan = TimeSpan.FromMilliseconds(timeMsSinceMidnight);
First step is to convert string to DateTime. Use DateTime.TryParse(string value, out DateTime dt). Then as Mathew Watson rightly suggested, get the value of variable dt converted to milliseconds using dt.TimeOfDay.TotalMilliseconds. It is also possible to convert the span in TotalSeconds or TotalMinutes if it suits your requirement.
Try to avoid calling ToString() method directly before checking if cell value is null. If I want to avoid the check, I would make compiler to do it by using something like : Rows[3].Cells[2].Value + "" instead of Value.ToString().
Mixing Mathew's and Mukesh Adhvaryu's answers, I got into this one, and it fits perfectly on what I need, thank you guys for your support!
txtAtiv.Text = dataGridView1.Rows[0].Cells[1].Value + "";
string value = dataGridView1.Rows[0].Cells[2].Value + "";
lblLeft.Text = value.Split(' ')[1];
textStatus.Text = "";
DateTime timeConvert;
DateTime.TryParse(value, out timeConvert);
double time;
time = timeConvert.TimeOfDay.TotalMilliseconds;
var timeSpan = TimeSpan.FromMilliseconds(time);
lblSoma.Text = timeSpan.ToString();
static void Main(string[] args)
{
string time1 = "11:15 AM";
string time2 = "11:15 PM";
var t1 = ConvertTimeToInt(time1);
var t2 = ConvertTimeToInt(time2);
Console.WriteLine("{0}", t1);
Console.WriteLine("{0}", t2);
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", ConvertIntToTime(t1));
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", ConvertIntToTime(t2));
Console.ReadLine();
}
static long ConvertTimeToInt(string input)
{
var date = DateTime.ParseExact(input, "hh:mm tt", CultureInfo.InvariantCulture);
TimeSpan span = date.TimeOfDay;
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", date);
return span.Ticks;
}
static DateTime ConvertIntToTime(long input)
{
TimeSpan span = TimeSpan.FromTicks(input);
var date = new DateTime(span.Ticks);
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", date);
return date;
}
Lets say I have the following DateTime variable
DateTime CurDate = '26/3/2014 12:00:00 AM';
I'm wondering how can I set the CurDate so that the value will become 26/3/2014 00:00:00 AM
Note that I still want the time, but with all zeros.
**P/S: The reason for having all zeros is because the datetime value stored in SQL Server is 26/3/2014 00:00:00.000. I need to cast CurDate to have all zeros in order to match database data
You can simply use
CurDate.Date and that will give you '26/3/2012 00:00:00'
Try to format DateTime:
DateTime dt = new DateTime(2014, 06, 21, 0, 0, 0);
Console.WriteLine(dt.ToString("dd.MM.yyyy HH:mm:ss tt"));
Result:
21.06.2014 00:00:00
More informations:
http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
You could try this one:
// Parse the string you have, to create a datetime.
DateTime CurDate = DateTime.ParseExact('26/3/2014 12:00:00 AM',
"dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
// Create the datetime you want based on the CurDate
DateTime result = new DateTime(CurDate.Year, CurDate.Month, CurDate.Day, 0, 0, 0);
For more information about ParseExact please have a look here.
Nowhere, in SQL Server or in .NET dates hasn't any presentation. They are just an numeric value. Don't care about that, both the SQL Server and .NET so smart that can pass parameters without any confusion. Just pass parameters of the correct data type.
Use 24 Hour Format
DateTime CurDate = DateTime.Parse("3/26/2014 12:00:00 AM");
Console.WriteLine("12 Hour Format: " + CurDate.ToString("dd-MM-yyyy hh:mm:ss"));
Console.WriteLine("24 Hour Format: " + CurDate.ToString("dd-MM-yyyy HH:mm:ss"));
I know it's late but I think this was the proper answer for future references:
Console.WriteLine("Current Date with 0s on time part: " + DateTime.Now.ToString("yyyy-MM-dd 00:00:00.000"));
this.dtGelisSaati = DateTime.Now;
set curency time values
this.dtGelisSaati = DateTime.Today;
this ok. zero time values set.
Put .Date and get the date part with zero time part.
I use Linq as:
var list = Results.Where(x => x.ExpDate.Date >= From.Date && x.ExpDate.Date <= To.Date).ToList();
I have a win form c# SQL app that stores date in one column and time in the another.
There is only one date time picker on my form and I want to display both date and time values (which are from two separate columns)..
So far this is what I've done
Datetime final = datetime. Parse exact (date + " " + time , "MM/dd/yyyy hh:mm tt", cultureinfo. Invariant culture);
But it throws " string was not recognized as valid datetime" exception on the above line.
If date and time are DateTime variables, you can combine them with date arithmetic:
DateTime date=...;
DateTime time = ...;
DateTime finalDate = date.Date + time.TimeOfDay;
If they are strings, you can parse them to DateTime and TimeSpan variables:
DateTime date=DateTime.ParseExact(dateString,dateFormat,CultureInfo.InvariantCulture);
TimeSpan time = TimeSpan.ParseExact(timeString,timeFormat,CultureInfo.InvariantCulture);
DateTime finalDate = date.Date + time;
This is possible because you can add a DateTime and a TimeSpan value to get a new DateTime value
You can use TimeSpan.Parse to parse
DateTime newDateTime = date.Add(TimeSpan.Parse(time));
string d = DateTime.Now.Date.ToString("dd/MM/yyyy");
string t = DateTime.Now.ToString("h:mm");
var ts = TimeSpan.ParseExact(t, #"h\:mm",CultureInfo.InvariantCulture);
DateTime result = DateTime.ParseExact(d, "dd/MM/yyyy", CultureInfo.InvariantCulture)+ts;
Hope this helps,
Thanks.
I have a date time variable DateTime d which has data.
I have string like this:
11:00 - 12:00
I want to take the date from the d variable then add the hour and minute from the string.
I did this:
string newStringDate = d.ToString("yyyy-mm-dd") + " "+hourValue.Split('-')[0];
DateTime dd = DateTime.Parse(newStringDate);
I got excpetion that the string can't be transfered to date.
I debug the code and I can see that the newStrinDate = 2014-01-25 11:00
what am i doing wrong please?
It should be like this
string newStringDate = d.ToString(#"yyyy\-MM\-dd") + " " + hourValue.Split('-')[0].Trim();
DateTime dd = DateTime.ParseExact(newStringDate, #"yyyy\-MM\-dd HH\:mm", null);
You can do even better (no need to convert original date to string):
DateTime dd = d.Date + DateTime.ParseExact(hourValue.Split('-')[0].Trim(), #"HH\:mm", null).TimeOfDay;