Create a appended string with separating date time with date in javascript - c#

I am doing something to prepare a string to display in a format in server side but now I have to replace it in javascript so my server side code is:
DateTime now = DateTime.Now;
string date = now.GetDateTimeFormats('d')[0];
string time = now.GetDateTimeFormats('t')[0];
txtFileName.Value = someString.Length > 10 ? someString.Substring(0, 10).TrimEnd() + "_" + date + "_" + time : someString.TrimEnd() + "_" + date + "_" + time;
txtFileName.Value = txtFileName.Value.Replace(' ', '_');
How to achieve that?

Although JavaScript provides a bunch of methods for getting and setting parts of a date object, it lacks a simple way to format dates and times according to a user-specified mask.
Check these date function and follow following links:
Formatting a date in javascript
How can I convert string to datetime with format specification in JavaScript?
var d = new Date();
var datepart = d.getDate() + " " + d.getMonth() + " " + d.getFullYear();
using Date object same you can create time format also.
To create filename format use javascript replaceenter link description here method
var myNewString = myOldString.replace("username", visitorName);
Check this to create trim method or extend javascript String Object
Hope this is enough to convert your server side code in java script...

check out DateJS, it has very powerfull date manipulation functions

Related

DateTime.ToString from all formats to dd/MM/YYYY?

I have a simple routine which parses a DateTime.Now & performs a .ToString() on it to add it into a file name to be saved:
DateTime timeNow = DateTime.Now;
string dateNow = timeNow.ToShortDateString();
DateTime dateTime = DateTime.ParseExact(dateNow, "dd/MM/yyyy", CultureInfo.InvariantCulture);
string DateString = dateTime.ToString("dd-MMM-yy");
string fileName = string.Concat("MyArticle_" + region + "_" + DateString + fileExtension);
this is the resulting output string:
MyArticle_Africa_07-May-15.PNG
This is all good until I get a user on an American machine where the DateTime settings are different e.g.
05-07-15
In this case my ParseExact() method throws an exception as the input is not a valid date time. Is there a way to accommodate all date time inputs & parse to dd/MM/YYYY?
Actually, you don't need all these lines of code. You just need this:
// We just have to pass to the ToString
// method the exact format we want. Under the hood the CLR has
// the know how to execute this command and you get the desired
// output.
string DateString = DateTime.Now.ToString("dd-MMM-yy");
Furthermore, we use the DateTime.ParseExact method, when we want to get this exception you have mentioned. Saying this, I mean that we know that the string representation of dates, which we want to parse are of the exact format, we have specified in DateTime.ParseExact and if some of them aren't we wan't to be informed know it. Usually, we would have a try catch clause and in the catch clause we log this.
You need to try this:
string DateString = DateTime.Now.ToString("dd-MMM-yy");
string fileName = String.Concat("MyArticle_" + region + "_" + DateString + fileExtension);
You don't even need to convert DateTime.Now to a string, you can create the entire string in one step using String.Format :
var fileName = String.Format("MyArticle_{0}_{1:dd-MMM-yy}{2}",
region,DateTime.Now,fileExtension);
or
var fileName = String.Format(CurrentInfo.InvariantCulture,
"MyArticle_{0}_{1:dd-MMM-yy}{2}",
region,DateTime.Now,fileExtension);
to avoid internationalization issues.

How to format date in javascript returned from ajax request to c# web api?

I am making a GET request to a web api on a different server to get a C# DateTime object. I want its formatting to stay in the C# format like:
6/11/2014 6:46:43 PM
However, the formatting gets changed once I retrieve it in my javascript function like this:
2014-06-11T18:46:43.2730485Z
How do I preserve the formatting, or how do I convert it back to the original format?
You could create a Date object, and then build a string from it.
var d = new Date(returnedDate);
var month = d.getMonth() + 1, // month indexed from 0-11
day = d.getDate(),
year = d.getFullYear(), // use instead of getYear() for 4-digit year
hour = d.getHours(),
minute = d.getMinutes(),
second = d.getSeconds();
// Convert to 12-hour time, if that's your thing
if (hour >= 12) {
hour -= 12;
var meridiem = 'AM';
// Correct for midnight
if (hour === 0) hour = 12;
} else {
var meridiem = 'PM';
}
var dStr = month + '/' + day + '/' + year + ' ' +
hour + ':' + minute + ':' + second + ' ' + meridiem;
I'm unfamiliar with C#'s conventions for dates, but that looks pretty close to what you want. Note that this will interpret the time in the local timezone. Normalizing that mostly requires using the UTC methods for the Date object.
Being real here: JavaScript's date libraries are... lacking. I really do recommend using a library for this. I like Moment.js a lot. Read up on parsing a date string and formatting a date for display.

System.Date in .ics file

I am attaching a .ics file with a email I send to the user. It works fine except the date and time. Currently I get system date and time when I double click on the attached .ics file. I couldn't add my own date columns value which I get from database to the calendar. Really appreciate some help.
Here is the contents for the .ics file:
string calLocation = eventRecordAfterInsert.location;
string calSubject = eventRecordAfterInsert.eventName;
string calDescription = "Event Schedule Description";
DateTime? calDate = eventRecordAfterInsert.eventDt;
DateTime? calTime = Convert.ToDateTime(row.Cells[11].Text);
DateTime calEventDateAndTime = calDate.Value.Date + calTime.Value.TimeOfDay;
String[] contents = { "BEGIN:VCALENDAR",
"VERSION:2.0",
"PRODID:-//flo Inc.//FloSoft//EN",
"METHOD:PUBLISH",
"BEGIN:VEVENT",
//"UID:{0}",
"DTSTAMP:" + calEventDateAndTime,
"DTEND:" + calEventDateAndTime,
"Location:"+ calLocation,
"Description;Encoding=QUOTED-PRINTABLE:" + calSubject,
"Summary:" + calDescription,
"Priority:3",
"BEGIN:VALARM",
"TRIGGER:-PT15M",
"ACTION:DISPLAY",
"DESCRIPTION:Reminder",
"END:VALARM",
"END:VEVENT", "END:VCALENDAR" };
System.IO.File.WriteAllLines(Server.MapPath("EventDetails.ics"), contents);
Date strings within an ICS file should be in the yyyyMMddTHHmmssZ format. So instead of:
"DTSTAMP:" + calEventDateAndTime,
You should do:
"DTSTAMP:" + calEventDateAndTime.ToUniversalTime().ToString("yyyyMMddTHHmmssZ"),
Or since you're repeating the value, move it out into another variable before appending it into your string array.
You are also trying to add a DateTime's time component to another DateTime with a date component, but I don't think it's going to work the way you want it to. You'll have to rethink that approach, perhaps parsing the time component out of the cell and adding that to the date:
DateTime? calDate = eventRecordAfterInsert.eventDt;
TimeSpan calTime = TimeSpan.Parse(row.Cells[11].Text);
DateTime calEventDateAndTime = calDate.Value.Date.Add(calTime);
Or combining the two DateTime structs into third new one:
DateTime calEventDateAndTime = new DateTime(calDate.Value.Year,
calDate.Value.Month,
calDate.Value.Day,
calTime.Value.Hour,
calTime.Value.Minute,
calTime.Value.Second);
Also, you aren't checking if calDate or calTime have values either, so I don't see the point in making them Nullable<DateTime>s.

Simplify string splitting

I am getting a result like this "PR242714031213" from a SQL query. This is basically a string PR + ssmmHHddMMyy. I need to extract and format it to a simple date ddMMyyyy.
I am using the following snippet with substrings which is working:
string rawDate = (string)lastProjaddedDate.ExecuteScalar();
string year= rawDate.Substring(12,2);
string month=rawDate.Substring(10,2);
string day=rawDate.Substring(8,2);
string date = day + "/" + month + "/" +"20"+ year;
Label4.Text =date;
I am wondering if I can simplify the code to get the ddMMyyyy out of it.
PS: I know I need to change the way it is codified in the DB to avoid problems in few decades but lets start to simplify it.
You can do:
Step - 1: Strip `PR` from the string
Step - 2: Parse to .Net `DateTime` object
Step - 3: Format to required format
Code :
string rawDate = "PR242714031213";
rawDate = rawDate.Substring(2);
DateTime dt;
if (!DateTime.TryParseExact(rawDate,
"ssmmHHddMMyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//invalid date
}
string formattedDate = dt.ToString("ddMMyyyy");
In one statement it would be:
string formattedDate = DateTime.ParseExact(rawDate.Substring(2),
"ssmmHHddMMyy",
CultureInfo.InvariantCulture)
.ToString("ddMMyyy");
Assuming you update the way dates are stored in the DB all you need is:
DateTime.ParseExact(rawDate.Substring(2), "ssmmHHddMMyyyy", CultureInfo.InvariantCulture).ToString("ddMMyyyy");
Otherwise use the following for the time being:
DateTime.ParseExact(rawDate.Substring(2), "ssmmHHddMMyy", CultureInfo.InvariantCulture).ToString("ddMMyyyy");
In any case you can choose whatever format you wish in the ToString() method.
A regular expression will give you terse code with validation as a bonus:
var match = Regex.Match(rawDate, #"PR\d{6}(?<d>\d\d)(?<m>\d\d)(?<y>\d\d)");
string date = match.Groups["d"].Value + "/" + match.Groups["m"].Value + "/20" + match.Groups["y"].Value;

Windows Service gives String was not recognized as a valid DateTime exception but the same code running properly in Console Application

Windows Service gives String was not recognized as a valid DateTime exception but the same code running properly in Console Application
Object max = cmd.ExecuteScalar(); //max will have 6/30/2012 12:00:00 AM
DateTime currentDt = DateTime.Now;
currentDt = DateTime.ParseExact(max.ToString(), "M/d/yyyy h:mm:ss tt", CultureInfo.CurrentCulture.DateTimeFormat); //This Line Gives Error in WindowsService Only
StreamWriter sw = new StreamWriter("E:\\ram\\SampleService.txt", true);
sw.WriteLine(currentDt.ToString());
sw.Close();
I even Changed System DateTime Format Settings to Engish - Us Settings.ShortDatetime is M/d/yyyy and Longtime is h:mm:ss tt.
Can someone help me resolve this issue?
My guess is that the system locale isn't the same as your user locale. If your system locale uses something other than "/" as the date separator, it will fail to match the "/" in your format string.
I suggest you change to use CultureInfo.InvariantCulture, at which point it should work - if the value of max.ToString() is actually "6/30/2012 12:00:00 AM". Have you validated that in the case it's failing, that's the value you're getting?
If your value is coming from a database though, why is it stored as a string to start with? Are you sure it even is a string? If it's actually a DateTime, then when you call ToString() you'll be using the current culture's default format to convert it - which could easily fail on the way back. Even if it is a string at the moment, does it really have to be? The fewer string conversions you can introduce, the better.
(As an aside, it's simpler to use File.WriteAllText or File.AppendAllText than using a StreamWriter like this. If you do need to use a StreamWriter, remember to use a using statement to dispose of the resource properly.)
Does your SQL request return DateTime or String value?
Also I don't see why do you use ParseExact in this case. In your case I would suggest to use Parse method with InvariantCulture parameter:
currentDt = DateTime.Parse(max.ToString(), CultureInfo.InvariantCulture);
If your max value is DateTime then you don't need to do parsing at all. You just need to check if it is DBNull.Value:
if (max != DBNullValue)
{
currentDt = (DateTime)max;
}
Try it without the CultureInfo:
currentDt = DateTime.ParseExact(max.ToString(), "M/d/yyyy h:mm:ss tt", null);
I got same problem when i had been building windows service.In that, i tryed to convert string date to datetime format. For that i used format string date_time = Day + "/" + Mn + "/" + Yr + " " + Hr + ":" + Min; and tryed convert it to datetime().
This format was running properly in windows form application but not in Windows service project.
Solution :
I changed above string format with this format string date_time = Mn + "/" + Day + "/" + Yr + " " + Hr + ":" + Min;, And then passed it to datetime().
Like follow :
string date_time = Mn + "/" + Day + "/" + Yr + " " + Hr + ":" + Min;
DateTime dt_1 = Convert.ToDateTime(date_time);
By default the en-US culture is used by .NET according to which the Date is in Month/Day/Year format
This is 100% working.

Categories