Reputation: 67
I have the option of using either JavaScript or c# to accomplish this task.
I have a lot of strings in the format "10/14/2012 8:45:34 PM" How do I remove the seconds and retain the PM like so "10/14/2012 8:45PM"?
I can't use substring because the length of the string will be different with each day and time.
Upvotes: 2
Views: 8691
Reputation: 1554
You can make use of Regular Expression for string manipulation and is pretty easier.
var mydate = "10/14/2012 8:45:34 PM";
var formated_date = mydate.replace(/(\d{1,2})\/(\d{1,2})\/(\d{4})\ (\d{1,2}):(\d{1,2}):(\d{1,2})\ (.*)/, "$1/$2/$3\ $4:$5$7");
document.write(formated_date);
Upvotes: 1
Reputation: 21
I tried using ToString()
in Axure JavaScript for setting text of widgets, but failed, and regex in Axure is out of the question (at least, at the time I posted this), so I had figured out another simple alternative, but inefficient method of doing it:
aDate.toLocaleTimeString().replace(':'+aDate.getSeconds(),'')
Upvotes: 0
Reputation: 285
well, you could try:
var string="10/14/2012 8:45:34 PM";
var resultArray = string.split(":");
var result = string.replace(resultArray[2],"");
which should work effectively in javascript. ill test it out in a second, and update this.
UPDATE:
var string="10/14/2012 8:45:34 PM";
var resultArray = string.split(":");
var result = string.replace(":"+resultArray[2]," ")+resultArray[2].split(" ")[1];
A tad yucky. but it works just fine: http://jsfiddle.net/x8uUW/
UPDATE using regex (i used a regex generator, so it is not as compact as it could be, by any means. but it does work: http://jsfiddle.net/x8uUW/1/
Upvotes: 0
Reputation: 700262
You can use a regular expression.
C#:
string d = "10/14/2012 8:45:34 PM";
d = Regex.Replace(d, @":\d\d ", String.Empty);
Javascript:
var d = "10/14/2012 8:45:34 PM";
d = d.replace(/:\d\d /, '');
Upvotes: 2
Reputation: 69372
In C#, you can do this:
myTime.ToString("MM/dd/yyyy hh:mmtt");
Alternatively, you can use the built in Format Specifiers
described here.
Edit - I removed the space between mm
and tt
because I just noticed your post shows 8:45PM
. You can add a space between mm
and tt
if you want it to be 8:45 PM
.
Upvotes: 10
Reputation: 147363
If the string is consistently formatted, then:
var s = '10/14/2012 8:45:34 PM';
s = s.replace(/:\d+ (\w\w)$/, '$1'); // 10/14/2012 8:45PM
I hope that is only going to be used by a very limited audience since that format will be misunderstood by the vast majority of people. A more widely understood and much less unambiguous format is:
2012-10-14 8:45PM
Upvotes: 3