Can Javascript Find And Replace Digit Dates to Formatted Dates? - javascript

can someone help me with a javascript regex question?
I am trying to replace all the digit dates in a string to a formatted version.
This is what I have so far
txt = txt.replace(/\d{10}/g, 'Formatted Date Here');
Is this possible? Any help is greatly appreciated! Thanks!

Try this:
str = str.replace(/\d{10}/g, function($0) {
return new Date($0*1000);
});
Date accepts a time in milliseconds. That’s why you multiply the match (passed in $0) with 1000.
If you want a different format than the default format, take a look at the methods of a Date instance. Here’s an example:
str = str.replace(/\d{10}/g, function($0) {
var d = new Date($0*1000);
return (d.getMonth() + 1) + ", " + d.getDate() + ", " + (d.getHours() % 12 || 12) + ":" + d.getMinutes() + " " + (d.getHours() < 12 ? 'AM' : 'PM');
});
The JavaScript Date.format functon Amarghosh posted here might help you.

You can use replace() with a function callback to achieve this:
var txt = "This is a test of 1234567890 and 1231231233 date conversion";
txt = txt.replace(/\d{10}/g, function(s) {
return new Date(s * 1000);
});
alert(txt);
outputs:
This is a test of Sat Feb 14 2009 07:31:30 GMT+0800 and Tue Jan 06 2009 16:40:33 GMT+0800 date conversion
You will need to adjust this to use the correct date format. Also you will need to consider the issue of time zones. The time zone on the client isn't necessarily the same as that on the server.
You might even be better off formatting the date on the server to avoid such issues.

Are you sure you want to use regex? Here is a JavaScript Date format function that you might want to check out.

Related

JavaScript -- slice time string to return HH:MM

I have a time/date string that is returned like so:
"5/31/2016, 2:23:33 PM". I need only the HH:MM and am/pm, so 2:23 PM
I am able to split the date off but not sure how I can remove the colon and seconds.
time = time.split(",")[0];
//time = " 2:23:33 PM";
thanks
If starting with a date/time string and desiring to end with a time string, of the same format, consider the following regular expression with two capture groups:
var dateStr = "5/31/2016, 2:23:33 pm";
var m = dateStr.match(/(\d{1,2}:\d{2}):\d{2}\s+?(AM|PM)/i)
// ^-- 1 ^-- 2
if (m) {
console.log(m[1] + " " + m[2].toUpperCase()); // "2:23 PM"
}
Otherwise, if ever needing to deal with a proper date/time object I'd consider moment.js - and specify the appropriate conversion format.
I would not use new Date(nonISO8601String) for parsing as it is unreliable across browsers/localizations.
I suggest using moment.js to parse the string and then output as a formatted string like this
var input = "5/31/2016, 2:23:33 PM";
var result = moment(input);
console.log(result.format("hh:mm a"));
//output: 02:23 pm
Fiddle
Update
As others have mentioned, although this answer does work as expected, that may not be the case across all browsers and locales the same.
My recommendation would preferably to use one of the popular date libraries like Moment.js, which could be argued as the de facto standard at the present time for handling this.
Using a Date Object
While this is entirely feasible through a series of splits, regular expressions, etc, it may simply be easier to just use some of Javascript's built-in Date functionality (assuming that your format isn't going to vary wildly).
You could consider writing a function to parse your date as a Date object and then formatting it accordingly :
function formatDateStringAsTime(input){
var date = new Date(input);
// Determine if it is AM or PM
var ampm = date.getHours() >= 12 ? ' PM' : ' AM';
// Output what you need
return (date.getHours() % 12) + ':' + date.getMinutes() + ampm;
}
Additionally if you want to ensure you have two digits (i.e. zero padded values), you can use a bit of slicing to change that :
// Using this approach will pad your hours and minutes with zeros if necessary
return ('0' + (date.getHours() % 12)).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2) + ampm;
Example
formatDateStringAsTime("5/31/2016, 2:23:33 PM"); // yields 2:23 PM
var input = "5/31/2016, 2:03:33 PM";
input = formatDateStringAsTime(input);
console.log(input);
function formatDateStringAsTime(input) {
var date = new Date(input);
// Determine if it is AM or PM
var ampm = date.getHours() >= 12 ? ' PM' : ' AM';
return ('0' + (date.getHours() % 12)).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2) + ampm;
}
Consider Date-specific Libraries
As others have mentioned, if you are going to be performing this behavior frequently within your application, you might consider using a library like Date.js or Moment.js, which are designed for exactly this.
You can do it in two lines using this regex:
var a = new Date("5/31/2016, 2:23:33 PM");
var b = a.toLocaleTimeString().replace(/:\d{2}\s/,' ');
console.log(b)
Parsing of strings using the Date constructor (and Date.parse) is largely implementation dependent and inconsistent across browsers so should not be relied upon. If parsing is required, use a bespoke function or library, there are plenty to choose from.
But reformatting a string doesn't require parsing, just extracting the required values. There are any number of simple ways to manipulate the string, here are two (note that leading zeros for hours are typically only used for 24 hour time formats):
// Extract h:mm ap component of a string in m/d/y h:mm:ss ap format
function getTime(s) {
var b = s.split(/\D/);
function z(n){return (n<10?'0':'')+n}
return z(b[4]) + ':' + z(b[5]) + ' ' + s.slice(-2);
}
document.write(getTime('5/31/2016, 2:23:33 PM'));
And (though this doesn't add leading zeros):
document.write(
'5/31/2016, 2:23:33 PM'.replace(/[^\s]*,\s|:\d+\s/g,' ').trim()
);

new date() AngularJS time sent from a server GMT to your local computer

I get a response from a service and when the service returns it returns with a created server GMT date. The issue arises when I want to display the local date ex: 5-22-2016 I want to change the time to my local computer.
my response looks something like this:
createdDate: "2016-04-22 16:48 PM GMT"
description: "File Upload Success"
fileGuid:"62e7250c-d5ed-41e2-b5b2-4600094d9a7c"
fileSize:"191429"
There are 90 different objects in my array.
I am trying to use _each which iterates through all of my key value pairs:
_.each(data, function(value, key) {
console.log(key, value);
var strDateTime = value.createdDate;
var myDate = new Date(strDateTime);
data[key].createdDate = (myDate.toLocaleString()).split(',')[0];
console.log("data", data)
But it is working for some of created dates and the others are returning invalid any suggestions
According to ECMA-262 5.1 15.9.1.15 Date Time String Format, seems some of your data doesn't in the right format.
ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ.
So a better solution would be using the moment.js.
With moment.js you can update your code into,
moment('2016-5-5').toLocaleString() //'Tue May 05 2015 00:00:00 GMT+0800'
Also, for only the showing purpose, there is an angular directive version, angular-moment.
Hope this would help. :)
Thx for the notice from #RobG, I just replaced the MDN with ECMA-262.
and for moment("2016-04-22 16:48 PM GMT"), you can see from the picture below,
You should manually parse date strings. A library can help, but if you only have one format, a bespoke parsing function is fairly trivial.
If the dates are always GMT and in the format '2016-04-22 16:48 PM GMT', a function like the following may suit.
If you want the output string in a particular format, you can use toISOString, which returns a string in ISO 8601 format with GMT time zone, or you can write a small formatting function to generate the format you require.
var s = '2016-04-22 16:48 PM GMT';
// Return a Date given a string in format 2016-04-22 16:48 PM GMT
function parseSpecial(s) {
var b = s.split(/[-\s:]/);
var h = (b[3]%12) + (/pm/i.test(s)? 12: 0);
return new Date(Date.UTC(b[0], b[1]-1, b[2], h, b[4]));
}
// Return a string in format mm/dd/yyyy hh:ss a given a date
function myFormat(date) {
function z(n){return (n<10?'0':'') + n}
var h = date.getHours();
var ap = h > 11? 'pm' : 'am';
h = h%12 || 12;
return z(date.getMonth() + 1) + '/' + z(date.getDate()) + '/' +
date.getFullYear() + ' ' + z(h) + ':' + z(date.getMinutes()) +
' ' + ap;
}
var d = parseSpecial(s);
document.write(s + // Original string
'<br>' + d.toISOString() + // As ISO 9601 long format string
'<br>' + myFormat(d) // As local date and time
+ ' (your local date and time equivalent)');
You an use a library to do all of the above, but whether one is necessary or not is up to you. For example, using moment.js, you'd do:
// Parse the string, passing the format
var s = '2016-04-22 16:48 PM GMT';
var d = moment(s.replace('GMT','Z'), 'YYYY-MM-DD hh:mm a Z');
// Create a string for local time in the required format
console.log(d.format('DD/MM/YYYY hh:mm a'));

How do I set the correct date in jQuery?

I try to get the correct date format, like this: 24-7-2015.
date = new Date("24-7-2015").toString({ dateFormat: 'd-M-yy' })
but the output of date is then: Wed Dec 7 00:00:00 UTC+0100 2016
Thank you
See this answer
If you want to make it easely, like in your example try to use momentjs
moment('24-7-2015', 'D-M-YYYY').format('DD-MM-YY');
Please try with the below code snippet.
var date = new Date("24-7-2015") // If this is not worked than check your local system date format
document.write(date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear());
Let me know if any concern.

Parse & format javascript date: dd M YYYY to YYYY-mm-dd

I have a date which looks like:
30 Apr 2015
How do I parse and display the date like this (without Moment.js)?
2015-04-31 (or YYYY-mm-dd)
The easiest thing to do might be to use moment.js.
If you prefer rolling your own solution in vanilla JS, this will work:
var padZero = function (integer) {
return integer < 10 ? '0' + integer : '' + integer
};
var myDate = new Date('30 Apr 2015');
var myDateString = myDate.getFullYear() + '-' +
(padZero(myDate.getMonth()+1)) + '-' +
(padZero(myDate.getDate()));
console.log(myDateString); // 2015-04-30
The parsing part is easy...though it'll fail on your example, because there is no 31st day in April :)
var x = new Date("30 Apr 2015");
Formatting the date is a little trickier. You have a few options. Date natively supports several output methods (.toDateString(), .toLocaleDateString(), etc) but none of them match the format you've given. It does, however, allow you to individually select the day, month and year values for the date. So, you can assemble them manually:
console.log(x.getFullYear() + '-' + (x.getMonth()+1) + '-' + x.getDate())
Note here that .getMonth() returns a 0-based index and isn't padded to two digits, and .getDay() gets the day-of-the-week index, not day-of-the-month (which is .getDate()).
However, your better choice is to take a look at moment.js, which provides the ability to format by an arbitrary format string, similar to what you'd expect from other languages. Unless you're unable to introduce another library for some reason, I feel this is a category of problem where it makes sense to use the very nice solution that already exists.
Use moment.js
Convert your date like this:
var myDate = moment("30 Apr 15", "DD MMM YY").format("YYYY-MM-DD");
console.log(myDate);
//2015-04-30
DEMO
you can do that easy with
//define Date
var xdate = "31 Apr 2015";
// simple array to define months from Jan to Dec [01 : 12]
var months = {
Jan:'01',
Feb:'02',
Mar:'03',
Apr:'04',
May:'05'
};
// split our Date and rearrange as yyyy-mm-dd
var reform = xdate.split(' ')[2]+'-'+months.Apr+'-'+xdate.split(' ')[0];
alert(reform);// return 2015-04-31

Making a basic date(technical)

NO JQUERY! I have a drop down in which the user selects a day month and year. I create the following code and pass these values into the variable using setFullYear. At times I also add days to this variable which is waht the variable ev_num is for. When I write this to the page it displays a lot of unnecessary info...
Sat Jan 01 2011 11:44:26 GMT-0500 (Eastern Standard Time)
I want it to simply read 'Jan 01 2011' or something like that. Does anyone know how I would fix this. Here is a jsfiddle of the entire page... http://jsfiddle.net/fET6v/
var myDate=new Date();
var ev_num = parseInt(document.getElementById("leave").value)
myDate.setFullYear(sel_year.value,sel_month.value,sel_day.value);
var event_value = document.getElementById("leave").value;
var d = new Date();
var day = d.getDate();
var year = d.getFullYear();
var month = d.getMonth();
var months=["Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct"," Nov","Dec"];
var currentMonth = months[month];
document.write(currentMonth + " " + day + " " + year);
This will print today's date with abbreviated months. It's fully customizable.
http://jsfiddle.net/iansan5653/u7hkE/
EDIT: See this demo for the leading zero in front of the day number: http://jsfiddle.net/iansan5653/u7hkE/1/
If you don't want the time and timezone to appear, use the .toDateString method instead of the simple toString. If you want a custom format, you will need to build the string yourself, you can get the single year/month/date values with the respective methods from your Date object. There are some (googlable) libraries to do that, a single method for your case would be
function myDateString(date) {
return ["Jan","Feb","Mar", …][date.getMonth()] +
" "+("0"+date.getDate()).substr(-2) +
" "+date.getFullYear();
}
http://blog.stevenlevithan.com/archives/date-time-format

Categories

Resources