Convert string in textbox to datetime column in sql - c#

Good day.
I'm very newbie in asp.net/c#/linq/etc, and I'm trying to figure it all out.
But it's need to do one small project.
In my view I have a table with datetime/string values and i need to insert this values to mssql database.
On View I have several Html.TextBox'es. By clicking button, TextBox is filled by current datetime.
View header(JS):
<script type="text/javascript">
function setDate(boxID) {
var dateNow = new Date();
var dd = dateNow.getDate();
var mm = dateNow.getMonth() + 1;
var yy = dateNow.getFullYear();
var hh = dateNow.getHours();
var MM = dateNow.getMinutes();
var ss = dateNow.getSeconds();
if (dd < 10) { dd = '0' + dd }
if (mm < 10) { mm = '0' + mm }
if (MM < 10) { MM = '0' + MM }
if (ss < 10) { ss = '0' + ss }
var today = dd + '-' + mm + '-' + yy + ' ' + hh + ':' + MM + ':' + ss;
document.getElementById(boxID).value = today;
}
</script>
View body:
<div class="divTableCell">
#Html.TextBox("p1_t1")
<input type="button" value="OK" onclick='setDate("p1_t1")' />
</div>
<div class="divTableCell">
#Html.TextBox("p1_notice")
</div>
<button id="result "type="submit">Insert data</button>
By clicking the last button i'm trying to insert this values to external database. Table contains columns p1_notice varchar(250) and p1_t1 datetime;
Controller:
public ActionResult EntranceInspection()
{
return View();
}
EntranceInspectionTableDataContext d = new EntranceInspectionTableDataContext();
public ActionResult EntranceInspectionResult()
{
EntranceInspection s = new EntranceInspection();
s.p1_notice = Request["p1_notice"]; // to SQL - ok
s.p1_t1 = Request["p1_t1"]; // error convert string to datetime
d.EntranceInspection.InsertOnSubmit(s);
d.SubmitChanges();
return View("EntranceInspection");
}
Is there any acceptable way to convert value in textbox to datetime and insert to datetime-column? Or I need to do something different at the start?
Thx

You should type cast the text value into the datetime like below.
s.p1_t1 = Convert.ToDateTime(Request["p1_t1"]);
This will help you to insert datetime value in database without error.

You must convert the text value into the datetime thus:
s.p1_t1 = Convert.ToDateTime(Request["p1_t1"]);
This will help you to insert datetime value in database without error. But, maybe can be usefull you garantie that p1_t1 has not a null value if in database the field is not nullabe.
If it is nullabe, you should insert datemin value or other value that is logical for your business.

You can try the following code ,
public ActionResult EntranceInspectionResult()
{
EntranceInspection s = new EntranceInspection();
s.p1_notice = Request["p1_notice"]; // to SQL - ok
s.p1_t1 = Convert.ToDateTime(Request["p1_t1"]);
d.EntranceInspection.InsertOnSubmit(s);
d.SubmitChanges();
return View("EntranceInspection");
}

Related

Date is not getting properly bound in my textbox Jquery

I want to show my date field in a textbox which is coming from Oracle database.
The scenario is, my date stored in DB column is 01-12-17 and its datatype is date.
and while binding it is coming as 1-11-17 I don't know why it's happening like this.
Here is my binding code.
if (getJSONValue.LAUNCH_DATE != "" || getJSONValue.LAUNCH_DATE != null) {
var newDate = new Date(getJSONValue.LAUNCH_DATE);
var day = newDate.getDate();
var month = newDate.getUTCMonth() + 1;
var year = newDate.getFullYear();
$('#txtLaunchDate').val(day + "-" + ((month)) + "-" + year.toString().substr(-2));
}
else {
$('#txtLaunchDate').val("");
}
When you call this :
var newDate = new Date(getJSONValue.LAUNCH_DATE);// if your date is 01-12-2017
the result is : Thu Jan 12 2017 00:00:00
It switches month and day info.
And as you try to add two values it contatenates :
var month = newDate.getUTCMonth() + 1; //returns 1 + 1 as string and the result is 11.
That that is why you see 1-11-17.
If you want a simple solution,
var str = getJSONValue.LAUNCH_DATE; //"01-12-2017";
var array = str.split("-");
var day = array[0];
var month = array[1];
var year = array[2].substr(2);
var dateStr = day + "-" + month + "-" + year;
Use getMonth instead of getUTCMonth:
var newDate = new Date('2017-12-01T00:00:00');
var day = newDate.getDate();
var month = newDate.getMonth()+1;
var year = newDate.getFullYear();
alert(day + "-" + ((month)) + "-" + year.toString().substr(-2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this
var month = (Number(newDate.getUTCMonth()) + 1);

Rendering in IE with fullcalendar

I am using the fullcalendar,
but in IE 10 or 11 the events are not render correct,
I have this:
public static List<DiaryEvent> LoadAllAppointmentsInDateRange(double start, double end)
{
var fromDate = ConvertFromUnixTimestamp(start);
var toDate = ConvertFromUnixTimestamp(end);
using (LolaBikeContext ent = new LolaBikeContext())
{
var rslt = ent.AppointmentDiarys.Where(s => s.DateTimeScheduled >= fromDate && System.Data.Entity.DbFunctions.AddMinutes(s.DateTimeScheduled, s.AppointmentLength) <= toDate);
List<DiaryEvent> result = new List<DiaryEvent>();
foreach (var item in rslt)
{
DiaryEvent rec = new DiaryEvent();
rec.ID = item.Id;
rec.SomeImportantKeyID = item.SomeImportantKey;
rec.StartDateString = item.DateTimeScheduled.ToString("MMMM/dd/yyyy"); // "s" is a preset format that outputs as: "2009-02-27T12:12:22"
rec.StarEvent = item.DateTimeScheduled.ToString("HH:mm"); // ParseExact(start, "HH:mm", CultureInfo.CurrentCulture).ToString(); //item.DateTimeScheduled.ToString("MMMM/dd/yyyy");
rec.EndDateString = item.DateTimeScheduled.AddMinutes(item.AppointmentLength).ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz");// "yyyy-MM-ddTHH:mm:ss.fffZ"); // field AppointmentLength is in minutes
rec.Title = item.Title;// +" - " + item.AppointmentLength.ToString() + " mins";
rec.AppointmentLength = item.AppointmentLength.ToString();
rec.StatusString = Enums.GetName<AppointmentStatus>((AppointmentStatus)item.StatusENUM);
rec.StatusColor = Enums.GetEnumDescription<AppointmentStatus>(rec.StatusString);
string ColorCode = rec.StatusColor.Substring(0, rec.StatusColor.IndexOf(":"));
rec.ClassName = rec.StatusColor.Substring(rec.StatusColor.IndexOf(":") + 1, rec.StatusColor.Length - ColorCode.Length - 1);
rec.StatusColor = ColorCode;
result.Add(rec);
}
return result;
}
}
and especially this line:
rec.EndDateString = item.DateTimeScheduled.AddMinutes(item.AppointmentLength).ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz");// is not rendering correct.
I have read that it has to be in: ISO 8601, so I have looked at this thread:
Given a DateTime object, how do I get an ISO 8601 date in string format?
but that doesnt work. IE is rendering the events not correct
Thank you!!
see the different pictures
The correct image:
I think youare missing the "s" format specifier, which is described as Sortable date/time pattern; conforms to ISO 8601
The EventStart comes in ISO 8601 format and you will need to convert it. you can follow this example to convert current to ISO 8601:
DateTime.UtcNow.ToString ( "s", System.Globalization.CultureInfo.InvariantCulture )
Here's a post about that : Link
As for your code try this instead for your startdatestring and enddatestring:
rec.StartDateString = item.DateTimeScheduled.ToString("s");
rec.EndDateString = item.DateTimeScheduled.AddMinutes(item.AppointmentLength).ToString("s");

insert date of birth into sql server

I made a JavaScript for date of birth, when debugging you choose your day of birth in three drop down boxes. One for days one for months and one for years. I'm working on C# asp.net. The problem is when i click on test(which is submit or confirm) the date is not taken to the database table. It fills empty! Any help would be appreciated..
here's the code:
DateOfBirth.js:
function date_populate(dayfield, monthfield, yearfield)
{
var today = new Date();
var dayfield = document.getElementById(dayfield);
var monthfield = document.getElementById(monthfield);
var yearfield = document.getElementById(yearfield);
for (var i = 0; i < 32; i++)
{
dayfield.options[i] = new Option(i , i + 1)
dayfield.options[today.getDate()] = new Option(today.getDate(), today.getDate(), true, true)
}
for (var m = 0; m < 12; m++)
{
monthfield.options[m] = new Option(monthtext[m], monthtext[m])
monthfield.options[today.getMonth()] = new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true)
}
var thisyear = today.getFullYear()
for (var y = 0; y < 100; y++)
{
yearfield.options[y] = new Option(thisyear, thisyear)
thisyear -= 1
}
yearfield.options[0] = new Option(today.getFullYear(), today.getFullYear(), true, true)
}
Form.asp.cs
protected void Button1_Click(object sender, EventArgs e)
{
String D, M, Y, Full;
D = Day.Value.ToString();
M = Month.Value.ToString();
Y = Year.Value.ToString();
Full = D + "/" + M + "/" + Y;
}
Don't construct dates as strings. Pass them as dates. For example:
DateTime dob = new DateTime(Year.Value, Month.Value, Day.Value);
...
cmd.Parameters.AddWithValue("dob", dob);
where the cmd.CommandText involves #dob when you want to refer to the date of birth.
Format the date 'yyyy-mm-dd' and it will insert.
Are you using a stored procedure?
Change your SP parameter from SqlDbType.NVarChar to SqlDbType.DateTime and then pass the date as a DateTime object to the parameter. You dont need to worry about conversions anymore.
DateTime dateofbirth = new DateTime(Convert.ToInt32(yearfield.SelectedValue),Convert.ToInt32(monthfield.SelectedValue), Convert.ToInt32(dayfield.SelectedValue));
param[0] = new SqlParameter("#DateOfBirth", SqlDbType.DateTime);
param[0].Value = dateofbirth;

Convert Javascript time string to DateTime or TimeSpan in MVC Controller

How do I covert JavaScript string "5:00 PM" to DateTime or TimeSpan when it get send to the MVC controller. I am using
bootstrap-timepicker
// usage
<script type="text/javascript">
$('#timepicker1').timepicker();
</script>
Javascript payload
{
Skip: 0
Status: []
Take: 15
DueTime: "1:00 PM" // keep in mind that this is a string
}
Server Object would be something like
class TimeSheet
{
public TimeSpan DueTime;
}
Use DateTime.Parse. Convert on server(on controller) when your string would transmit with your time.
http://msdn.microsoft.com/ru-ru/library/system.datetime.parse(v=vs.110).aspx
Okay so I read everyhting wrong hence the deleted answer.. !
But I'm not giving up ;)
Your bootstrap-timepicker, will give you a time as this "1:00 PM".
But before that we are going to look on the serverside to see what we can parse into a datetime object.
This is C# for parsing datetime.
string dateString, format;
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "15/08/2000 16:58"
format = "dd/MM/yyyy HH:mm"
result = DateTime.ParseExact(dateString, format, provider);
Now as you se your string wont look like that I'm going to assume that you want todays date!
This is function I tend to use most of the times when converting, to 24H clock.
function ConvertTimeformat(str) {
var time = str;
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if (AMPM == "PM" && hours < 12) hours = hours + 12;
if (AMPM == "AM" && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;
//Creating the todays date in the right format
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0!`
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
var todaysdate = dd+'/'+mm+'/'+yyyy +" " ; //<--I added an extra space!
var hoursNminutes = sHours + ":" + sMinutes
//CREATE THE RIGHT FORMAT FOR DATE.PARSEXACT "dd/MM/yyyy HH:mm"
var dateToParse = todaysdate + hoursNminutes
return dateToParse;
}
To Use the function do like this!
//Call it and provide your bootstrap time. And make it return to a variable
var dateToBeSentToServer = ConvertTimeformat("1:00 PM");
//OR With the bootstraptime as a variable
var dateToBeSentToServer = ConvertTimeformat(timevariable);
Now you can send dateToBeSentToServer to your serverside for parsing!

Convert DateTime To JSON DateTime

I have a WebService which return DateTime Field.
I get a result /Date(1379048144000)/ but
i want just 1379048144000 how can i achieve that.
[WebMethod]
public DateTime GetServerDate()
{
return DateTime.Now;
}
by setting Header Content-Type: application/json; charset=utf-8; i got a result like /Date(1379048144000)/.
You could change your WS to return a long with the value of the DateTime. The value to return is the number of milliseconds since the Unix Epoch (01/01/1970). This could be done with an extension method on DateTime something like:
public static class DateTimeExtensions
{
...
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1);
public static long ToUnixTime(this DateTime dateTime)
{
return (dateTime - UnixEpoch).Ticks / TimeSpan.TicksPerMillisecond;
}
...
}
And your web service method might look something like:
public long GetMyDate(...)
{
DateTime dateTime = ...;
return dateTime.ToUnixTime();
}
with Json.NET :
string date = Newtonsoft.Json.JsonConvert.SerializeObject(DateTime.Now);
in client side you can use this function to show a right date to client(I use it on my projects):
function parseJsonDate(jsonDate) {
var offset = new Date().getTimezoneOffset() * 60000;
var parts = /\/Date\((-?\d+)([+-]\d{2})?(\d{2})?.*/.exec(jsonDate);
if (parts[2] == undefined) parts[2] = 0;
if (parts[3] == undefined) parts[3] = 0;
d = new Date(+parts[1] + offset + parts[2] * 3600000 + parts[3] * 60000);
date = d.getDate() + 1;
date = date < 10 ? "0" + date : date;
mon = d.getMonth() + 1;
mon = mon < 10 ? "0" + mon : mon;
year = d.getFullYear();
return (date + "." + mon + "." + year);
};
This function is return right date in format: dd.mm.yyyy, but you can change it if you need. I hope that I help you.
U can always solve your problem when sending a date in a JSON object to JS by converting the date as follows:
var myJSDate = (new Date(parseInt(obj.MyDate.substr(6)))).toJSON();
Where obj.Date contains the date you wanna format.
Then u'll get something like this: "2013-10-25T18:04:17.289Z"
U can always check it in Chrome console by writing:
(new Date()).toJSON();
Hope this helps!
There are two solutions:
client side:
function ToJavaScriptDate(value) {
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(value);
var dt = new Date(parseFloat(results[1]));
return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
}
It is possible to need alsou to convert into data object
var date = new Date(xxx)
Server side:
Newtonsoft.Json.JsonConvert.SerializeObject(your_object)
Simply write like this to convert your date string in JSON format.
date = "{" + date + "}";
try regex:
var jsonDate = #"/Date(1379048144000)/";
var regex = /-?\d+/;
var jsonDate = re.exec(jsonDate);
var dateOriginal = new Date(parseInt(m[0]));

Categories