Format date in javascript AM and PM - javascript

I have this date 20/4/2016;4:23:00;PM
But i want to put in like this DD/MM/YYYY HH:mm:ss without the AM or PM
For example 20/04/2016 16:23:00
Thanks in advance
Carlos Vieira

In javascript the supported format for in your case is "MM/DD/YYYY hh:mm:ss AM" or "MM/DD/YYYY hh:mm:ss PM".
If you will give input like "04/20/2016 11:00:06 PM" then you will get an output as date format "Fri Mar 04 2016 23:00:06 GMT+0530 (IST)" which you can save it.
You can put "04/20/2016 11:00:06Z PM" mark here and get the result according to the UTC.
For reference https://www.w3schools.com/js/js_date_formats.asp

One approach is to reformat the string and convert the time part to 24hr time, e.g:
function reformatDate(s) {
var b = s.split(';');
var t = b[1].split(':');
var h = +t[0];
h = h%12 + (/pm/i.test(b[2])? 12 : 0);
return b[0] + ' ' + h + ':' + t[1] + ':' + t[2];
}
console.log(reformatDate('20/4/2016;4:23:00;PM')); // 20/4/2016 16:23:00
That avoids the vagaries of parsing the entire string to a date then reformatting it. If that's what you want to do, there are plenty of questions here already on parsing and formatting dates:
Where can I find documentation on formatting a date in JavaScript?
lots of parsing questions

Related

C# convert long datetime to get compatible with sql server datetime, date is coming from javascript [duplicate]

This question already has answers here:
Convert JavaScript Date to .NET DateTime
(4 answers)
Closed 5 years ago.
I am passing in a long date from javascript through web api and the date needs to be converted to end up being compatible with C# and then SQL Server datetime field.
This is What is getting passed in
Fri Sep 15 2017 00:11:44 GMT-0700 (US Mountain Standard Time
So I was just trying to do a Convert.ToDateTime
DateTime c = Convert.ToDateTime("Fri Sep 15 2017 00:11:44 GMT-0700 (US Mountain Standard Time)");
Says its not a valid DateTime, and if I don't use convert , then error is that I cannot convert a long to a string.
This probably needs to first be converted in javascript as I think that it will blow up with C# DateTime
However 2017-09-15T07:11:44.000Z is not correct from javascript is it?
From your example it also looks like you want to convert the local time into the equivalent GMT time. If this is the case, there's a great JavaScript library for date/time manipulation, moment.js, which will do that for you. moment().toISOstring() will take the JS user's current date time and give you a zulu time in ISO format.
string source = "Fri Sep 15 2017 00:11:44 GMT-0700";
var result = DateTimeOffset.ParseExact(
source.Replace("GMT", ""),
"ddd MMM dd yyyy HH:mm:ss zzz",
CultureInfo.CurrentCulture);
Use this piece of code to convert JavaScript long date to C# compatible format(dd/MM/yyyy):-
var date = new Date();
var newformateddate = function (date) {
var year = date.getFullYear();
var month = date.getMonth();
month++;
if (month < 10) {
month = "0" + month;
}
var day = date.getDay();
if (day < 10) {
day = "0" + day;
}
document.write(day + " / " + month + " / " + year);
}
Parse datetime with formate is the base way to convert it.
DateTime.ParseExact(dateString.Substring(0,24),
"ddd MMM d yyyy HH:mm:ss",
CultureInfo.InvariantCulture);

Javascript Date() in ReactJS: How to accept input as GMT/UTC and convert it into ISO string?

Currently the input is "12 09 2016 00:00:00" and should assume it is in inputted as GMT date and time. But rather, it accepts it as local and converts it as such. And when it is turned to ISOString(), it converts it to GMT, and adds the time difference.
How can I take an input in "12 09 2016 00:00:00" format, take it as GMT/UTC, and do .toISOString() to turn it into the ISO format, "2016-12-09T00:00:00.000Z"?
var dateAndTime = new Date("12 09 2016 00:00:00")
//Returns: "Fri Dec 09 2016 00:00:00 GMT-0800 (PST)"
//Want it to return: "Fri Dec 09 2016 00:00:00 (GMT)"
var gmtDateAndTime = dateAndTime.toISOString();
//Returns: "2016-12-09T08:00:00.000Z"
//Want it to return: "2016-12-09T00:00:00.000Z"
Thank you and will be sure to vote up and accept the answer.
How can I take an input in "12 09 2016 00:00:00" format, take it as
GMT/UTC, and do .toISOString() to turn it into the ISO format,
"2016-12-09T00:00:00.000Z"?
It seems you just want to reformat the string, so just do that:
// Reformat string in MM DD YYYY HH:mm:ss format to
// ISO 8601 UTC
function formatDateStringISO(s) {
var b = s.split(/\D/);
return b[2] + '-' + b[0] + '-' + b[1] +
'T' + b[3] + ':' + b[4] + ':' + b[5] + '.000Z';
}
console.log(formatDateStringISO('12 09 2016 00:00:00'))
If you want to parse the string to a Date then output an ISO 8601 format string, do that:
// Parse string in MM DD YYYY HH:mm:ss format
// If date string is invalid, returns an invalid Date
function parseDateAsUTC(s) {
var b = s.split(/\D/);
var d = new Date(Date.UTC(b[2], --b[0], b[1], b[3], b[4], b[5]));
// Validate date
return d && d.getMonth() == b[0]? d : new Date(NaN);
}
// Valid date Invalid date
['12 09 2016 00:00:00', '12 34 2016 00:00:00'].forEach(function(s) {
var d = parseDateAsUTC(s);
console.log(s + ' => ' + d[isNaN(d)? 'toString' : 'toISOString']());
});
You need to use another Date constructor. The default constructor creates time in your local timezone.
Replace this:
var dateAndTime = new Date("12 09 2016 00:00:00")
With this:
var dateAndTime = new Date(Date.UTC(2016, 09, 12, 0, 0, 0));
If you can't convert your string ("12 09 2016 00:00:00") manually to the individual UTC parameters, you can use this (but unreliable especially in IE):
var utcDate = Date.parse("12 09 2016 00:00:00");
Do not use Date to parse happenstance date strings. Date.parse only works in a well defined manner when the input is an ISO8061 string.
From "15.9.4.2 Date.parse" in the ECMA 5 standard:
The function first attempts to parse the format of the String according to the rules called out in Date Time String Format (15.9.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.
and from 15.9.1.15 the string format recognized is
YYYY-MM-DDTHH:mm:ss.sssZ
which looks very much the ISO string you want to arrive at, not start with.
Alternative choices to solve the issue might include:
write your own function to parse a user input string. Has the problem that "12 09 2016" could mean "Dec 9 2016" or "Sep 12 2016" depending on user locale.
Use a date and time library. Moment.js is frequently mentioned in SO answers regarding such libraries.
Use the output of a date picker or validated data from a data base. Avoids issues with locale dependent formats.
Hard code conversion to ISO8061 format without parsing may be an option if the input string is absolutely guaranteed to be in "mm dd yyyy hh:mm:ss" format, as for example using
function isoFromZ( str) {
return str.substr(6,4) + "-" +
str.substr(0,2) + "-" +
str.substr(3,2) + "T" +
str.substring(11) + ".000Z";
}
In summary extract the UTC date and time components from a custom input string before creating a Date object. If extraction produced an ISO8061 date string it can be passed directly to the Date constructor as a parameter.

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

Format the following date into YYYY-mm-dd in JS

How would I go about converting following date:
Thu Feb 18 12:25:00 SGT 2016
into a format like '2016-02-18'?
I know,
That, using a new Date(Date.parse('...')), with calls, will help me get it. But the problem being timezone part (SGT).
I dont want to use any libraries out there.
What would be the effective way to go about this?
Any help is appreciated!
PS:
Ok, I have tried
new Date(Date.parse('Thu Feb 18 12:25:00 SGT 2016'))
but of-course, it is going to me 'invalid date' error.
I guess I should wait for you to post some code, but here's an example. It splits the string into parts, converts the month name to a number, then outputs the bits you want in the order you want. The slice on the month name is just in case you want to use the full month name, but maybe that's unnecessary:
function reformatDate(s){
var b = s.split(/[\s:]/);
var months = {jan:'01',feb:'02',mar:'03',apr:'04',may:'05',jun:'06',
jul:'07',aug:'08',sep:'09',oct:'10',nov:'11',dec:'12'};
return b[7] + '/' + months[b[1].toLowerCase().slice(0,3)] + '/' + ('0'+b[2]).slice(-2);
}
document.write(reformatDate('Thu Feb 18 12:25:00 SGT 2016'));
That format date string (y/m/d) isn't consistent with any standard that I know of and likely will not be parsed by most browsers.
Why not just take the individual components of the date object and build a string from them?
full_date = new Date();
formatted_date_string = full_date.getFullYear() + "-" + (full_date.getMonth()+1) + "-" + full_date.getDate();
I'll leave it to you to sort out the leading 0s on the day and month.
var input="Thu Feb 18 12:25:00 SGT 2016";
var ar=input.split(" ");
var months = {"Jan":"01", "Feb":"02", "Mar":"03", "Apr":"04", "May":"05", "Jun":"06", "Jul":"07", "Aug":"08", "Sep":"09", "Oct":"10", "Nov":"11", "Dec":"12"};
console.log(ar[ar.length-1]+"-"+months[ar[1]]+"-"+ar[2]);
Try this code no date parsing required. Please check on console for result.
var date = "Thu Feb 18 12:25:00 SGT 2016";
date = date.replace("SGT","GMT+0800") // replaces SGT with GMT+0800 because
singapore time is 8 hrs ahead than GMT timezone
var newdate = new Date(Date.parse(date))
var requiredDate = newdate.toLocaleDateString()

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