Convert a AM/PM date string to JavaScript date using jQuery - javascript

I have a date string like this 20/09/2018 12:00 AM. I need to stop to put the previous date than today. I have searched the web for it, but no answer found with this format.
I need the default date format of JavaScript so that I can compare with new Date() value. When I use the following format it show the message that says invalid date because of my dd/MM/yyyy hh:mm tt format.
alert(new Date("20/09/2018 12:00 AM"));

Igor recommended using moment.js to solve this — it is a widely used date/time library.
With moment.js you can do this:
var m = moment("20/09/2018 3:14 PM", "DD/MM/YYYY h:mm a");
var d = m.toDate();
The first line creates a "moment" object by parsing the date according to the format string specified as the second argument. See http://momentjs.com/docs/#/parsing/
The second line gets the native javascript Date object that the moment object encapsulates; however, moment can do so many things you may not need to get back that native object.
See the moment docs.

Your format isn't valid, thus you're getting invalid date error. So, using your format(dd/MM/yyyy hh:mm tt) we'll grab the year, month, day, hours and the minutes, then we'll reformat it as an acceptable format by the Date constructor and create a Date instance.
Here's a function that do all what being said and returns a Date instance which you can compare it with another Date instance:
function convertToDate(str) {
// replace '/' with '-'
str = str.replace(/\//ig, '-');
/**
* extracting the year, month, day, hours and minutes.
* the month, day and hours can be 1 or 2 digits(the leading zero is optional).
* i.e: '4/3/2022 2:18 AM' is the same as '04/03/2022 02:18 AM' => Notice the absence of the leading zero.
**/
var y = /\-([\d]{4})/.exec(str)[1],
m = /\-([\d]{2}|[\d])/.exec(str)[1],
d = /([\d]{2}|[\d])\-/.exec(str)[1],
H = /\s([\d]{2}|[\d]):/.exec(str)[1],
i = /:([\d]{2})/.exec(str)[1],
AMorPM = /(AM|PM)/.exec(str)[1];
// return a Date instance.
return new Date(y + '-' + m + '-' + d + ' ' + H + ':' + i + ' ' + AMorPM)
}
// testing...
var str1 = '20/09/2018 12:00 AM';
var str2 = '8/2/2018 9:00 PM'; // leading zero is omitted.
console.log(convertToDate(str1));
console.log(convertToDate(str2));
The Date depends on the user's/server's location, two users may have
different results.
Learn more
about Date.
Hope I pushed you further.

Related

Why new date() is not accepting string and give invalid date?

Javascript:I have a function which has s parameter s contains this s=07:05:45PM;s has time which is in form of string i want to use it in new Date() but gives error i had to get hours mins seconds convert this time to 24 hour format please help me output:invalid date
function time Conversion(s) {
var date=new Date(s);
console.log(date);
}
According to specification, you can pass the dateString as a parameter to the Date constructor. There is a bunch of dateString format limitations, and in you case your dateString (named s) is invalid for date constructor (actually, your s is even has not any date, it consists of time only).
The possible solution is to handle your s parameter manually: cut verbal part, split time by :, then pass params to the Date constructor in sequence year, month, date, hours, minutes, seconds, or construct your own ISO String, format:
{year}-{month}-{date}T{hours}:{minutes}:{seconds}.{milliseconds}Z
Note, that hours in both cases should be in 24-hours format, so you should manually handle your 12-h formatted hours.
The reason you're getting an invalid Date from the built-in parser is covered by Why does Date.parse give incorrect results?
To convert a string like 07:05:45PM to 24 hour time, you can parse the parts and generate an new string, adding 12 to the hour if it ends in PM or not if it ends in AM (and change 12am to 00). e.g.
function to24HrFormat(s) {
var z = n => (n<10?'0':'')+n;
var b = s.match(/\d+/g);
var ap = /am$/i.test(s)? 0 : 12;
return z((b[0]%12) + ap) + ':' + b[1] + ':' + b[2];
}
// Tests
['07:05:45PM', '06:23:49AM', '12:15:00AM', '11:59:59pm']
.forEach(s => console.log(s + ' => ' + to24HrFormat(s)));
You should validate the input string, and maybe allow for missing seconds.
From the time string, remove the AM/PM (need to have a 24hr timestring)
var time = "07:05:45";
var datetime = new Date('1970-01-01T' + time + 'Z');
Now do your time based operations.
Try using Date.parse(string) instead. See referene.

JavaScript convert DateTime:"2017:10:01 19:06:57" string to ISO date string

I need to convert the following
DateTime:"2017:10:01 19:06:57"
To ISO date/time format I tried doing to image.exif.DateTime.toISOString()
But ran into an error, am I missing something?
You have to replace the first two colons by dashes. You can achieve that by .replace(/:(?=.* )/g, '-'), which in that case has the same effect as .replace(':', '-').replace(':', '-').
Additionally you have to replace the space by the letter T.
var dateString = "2017:10:01 19:06:57";
var dateStringISO = dateString.replace(/:(?=.* )/g, '-').replace(' ', 'T');
// (timezone indicator is optional)
console.log(dateStringISO); // That format fulfills ISO 8601.
var date = new Date(dateString.replace(/:(?=.* )/g, '-'));
// here you could manipulate your date
console.log(date.toISOString());
If, your browser doesn't support toISOString() method. try below code
function ISODate(d) {
function pad(n) {return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var d = new Date();
console.log(ISODate(d));
It is unlikely that any JS implementation will understand the format:
2017:10:01 19:06:57
Eg. in Chrome's dev tools:
08:28:08.649 new Date("2017:10:01 19:06:57")
08:28:08.649 Invalid Date
(Colons are typically time separators and no element of a time can be 2017.)
Therefore you're going to need to parse it yourself. Something like:
var year = parseInt(str.substring(0, 4));
var month = parseInt(str.substring(5, 7));
// etc for day, hour, min, sec
var d = new Date(year, month, day, hour, min, sec);
(This will create to a local time, if you want UTC then use Date.UTC rather than the constructor.)

Convert ISO date to international date type javascript

I want to filter data by current month (maybe additionally add next month data). I don't know how to go from the beginning.
In theory I think I could compare current month and month date from my data and then to display data only if two months variables match.
I thought I should start like this:
var myDate = new Date();
var thisMonth = new Date(myDate);
thisMonth.setMonth(myDate.getMonth()+1);
var nextMonth = new Date(myDate);
nextMonth.setMonth(myDate.getMonth()+2);
Thank you in advance for any kind of help!
Additional detailed explanation:
I copied SharePoint 2013 list whose data I displayed on SharePoint site page.
In content editor web part I wrote javascript code to show that list as a table.
I have two date columns (from/until) but they are displayed in table as YYYY-MM-DD HH:MM:SS. Looks to me like ISO date format. I saw several examples how to convert in js that type of date into date type like DD.MM.YYYY. None worked for me or I didn't know how to do it correctly. So I created calculated field that will present date type as text/string, after this I managed to show date on js table the way I wanted.
You should not parse strings with the Date constructor (or Date.parse, they are equivalent for parsing) as it's largely implementation dependent and notoriously unreliable.
I have two date columns (from/until) but they are displayed in table as YYYY-MM-DD HH:MM:SS. Looks to me like ISO date format.
Almost. The extended format is YYYY-MM-SSTHH:MM:SS, the T can be replaced by a space on agreement between parties exchanging the date but it's not strictly correct. If the timezone is omitted, it's treated as a "local" date (i.e. the host timezone offset is used in calculating the moment in time that it represents).
According to ECMA-262, if the format is not correct, browsers can either:
Treat it as invalid ISO 8601 and return an invalid date
Treat it as not ISO 8601 and fall back to whatever parsing algorithm they wish to use
So given:
new Date('2017-01-01 23:12:12')
Firefox returns a Date for 1 Jan 2017 23:12:12 in the host time zone, Safari returns an invalid date. Both are consistent with the standard.
So if you need a Date object, you should parse the string manually using either a library (e.g. fecha.js or moment.js) or a simple function.
But anyway, you don't need to parse the strings to a Date to reformat the string, just use string methods and avoid Date parsing vagaries completely.
function filterCurrentMonth() {
// Create string for comparison
var d = new Date();
var currentMonth = d.getFullYear() + '-' + ('0' + (d.getMonth()+1)).slice(-2);
// Hide rows that don't have string in the first cell
var rows = document.getElementById('t0').rows;
[].forEach.call(rows, function(row) {
if (row.cells[0].textContent.indexOf(currentMonth) == -1) {
row.style.display = 'none';
} else {
row.style.display = '';
}
});
}
function filterNone() {
var rows = document.getElementById('t0').rows;
[].forEach.call(rows, function(row) {
row.style.display = '';
});
}
#t0 {
font-size: 60%;
}
<button onclick="filterCurrentMonth()">Show only current month rows</button>
<button onclick="filterNone()">Show all rows</button>
<table id="t0">
<tr><td>2017-01-01 23:12:12<tr><td>2017-02-01 23:12:12<tr><td>2017-05-01 23:12:12
<tr><td>2017-03-01 23:12:12<tr><td>2017-04-01 23:12:12<tr><td>2017-12-01 23:12:12
<tr><td>2017-10-01 23:12:12<tr><td>2017-11-01 23:12:12<tr><td>2017-06-01 23:12:12
<tr><td>2017-07-01 23:12:12<tr><td>2017-09-01 23:12:12<tr><td>2017-08-01 23:12:12
<tr><td>2017-01-01 23:12:12<tr><td>2017-02-01 23:12:12<tr><td>2017-05-01 23:12:12
<tr><td>2017-03-01 23:12:12<tr><td>2017-04-01 23:12:12<tr><td>2017-12-01 23:12:12
<tr><td>2017-10-01 23:12:12<tr><td>2017-11-01 23:12:12<tr><td>2017-06-01 23:12:12
<tr><td>2017-07-01 23:12:12<tr><td>
<!-- begin snippet: js hide: false console: true babel: false -->
23:12:122017-08-01 23:12:12
Similarly, if you want to reformat the string to be DD.MM.YYYY you can just reformat the string:
/* Format string in YYYY-MM-DD HH:mm:ss format to DD.MM.YYYY
** #param {string} s - string in YYYY-MM-DD HH:mm:ss format
** #returns {string} in DD.MM.YYYY format
*/
function formatYMDtoDMY(s) {
var b = s.split(/\D/);
return b[2] + '.' + b[1] + '.' + b[0];
}
console.log(formatYMDtoDMY('2017-10-01 23:12:12'))
Note however that dates should use unambiguous formats like DD-MMM-YYYY, e.g. 01-Jan-2017. It only takes one more line of code for that. ;-)
Don't forget, getMonth() returns a Number, from 0 to 11, representing the month,
and Date make the date as object with methods and properties
There is a lot of examples here
var date = new Date('2010-10-11 00:00:00');
var formatDate = date.getDate() + '/'
+ (date.getMonth() + 1) + '/'
+ date.getFullYear();
console.log( formatDate );
So you can always pass the date on any format but there some important moments you can read here:
Converting string to date in js
Are you asking?
I don't know how to go from the beginning.
You could get the beginning from current month and the last date of next month by following code:
<html>
<script>
var myDate = new Date();
var thisMonth = new Date(myDate.getFullYear(), myDate.getMonth(), 1);
var nextMonth = new Date(myDate.getFullYear(), myDate.getMonth() + 2, 0);
console.log("Date start: " + thisMonth);
console.log("Date end: " + nextMonth);
console.log("Formatted date start: " + formatDate(thisMonth));
console.log("Formatted date end: " + formatDate(nextMonth));
function padLeft(n){
return ("00" + n).slice(-2);
}
function formatDate(){
var d = new Date,
dformat = [ d.getFullYear(),
padLeft(d.getMonth()+1),
padLeft(d.getDate())
].join('-')+
' ' +
[ padLeft(d.getHours()),
padLeft(d.getMinutes()),
padLeft(d.getSeconds())].join(':');
return dformat
}
</script>
</html>
I hope it helps you. Bye.

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'));

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

Categories

Resources