JavaScript date format convert. - javascript

Date from datetimepicker have format:
var currentDate = new Date(); currentDate = Thu Jul 14 2016 09:10:04 GMT+0200 (Środkowoeuropejski czas letni) {}
And this date have methods like .getFullYear() etc.
But when I send it to my API where this date is DateTime and send back it to frontend it look that 2016-07-22T22:00:00Z and it doesn't have methods like .getFullYear() etc.
That is problem for me. I need detect if the date is formatted yyyy-mm-ddThh-mm-ssZ and convert it to the first format.
How I can do it? I can't use momentjs.

format your date string in javascript
var date = new Date();
var day = date.getDay();
var month = date.getMonth();
var year = date.getFullYear();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
var datetime= day + "/" + month + "/" + year + " " + hour + ':' + minute + ':' + second;
Then in c#
DateTime.ParseExact(DatetimeString , "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

Why you do not use this:
http://momentjs.com/
this allows all sorts if formatting and its safer to use due to incorrect dates possible
var a = moment('2016-01-01');
var b = a.add(1, 'week');
a.format();
"2016-01-08T00:00:00-06:00"
moment().format("MMM Do YY"); // Jul 14th 16

Use standard format yyyy-mm-dd hh-mm-ss
You're possibly receiving a string from your API. So you have to parse it back to Date object
var newDateObject = new Date(dateStringFromAPI);
Then you can access newDateObject.getDay() newDateObject.getFullYear() etc

as you are using AngularJS you can simply format date with Angular's date filter https://docs.angularjs.org/api/ng/filter/date

Good day to you!
Looks like the front-end doesn't parse the API-dataset to create a date-object (no date-object—no date-methods)—here is a solution:
Enable date-parsing on the front-end;
If needed, apply a date-time format on API output (MSDN-articles: Date and Time Format Strings—Standard and Custom);
Send the API-processed data to the front-end.

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

How to specify timestamp format when converting to human readable string in JS

I need to display a formatted date from a timestamp provided by Google Analytics
Standard solution like
var date = new Date(timestamp * 1000);
var formatted = date.toString();
produces wrong value Jan 01 1970. That's because of timestamp format.
In PHP I can specify the timestamp format:
\DateTime::createFromFormat('Ymd', $timestamp);
How to do this in JS?
Since the dates you are receiving are formatted as YYYYMMDD, not as a Unix
timestamp, you can parse it by
extracting the year, month and date using String.prototype.slice.
var timestamp = '20170306',
year = parseInt(timestamp.slice(0, 4), 10),
month = parseInt(timestamp.slice(5, 6), 10),
day = parseInt(timestamp.slice(7, 8), 10);
// - 1 because the Date constructor expects a 0-based month
date = new Date(Date.UTC(year, month - 1, day)),
gmt = date.toGMTString(),
local = date.toString();
console.log('GMT:', gmt); // Mon, 06 Mar 2017 00:00:00 GMT
console.log('Local:', local);
This assumes that the dates you are using are in UTC (which they likely are). Date.UTC creates a timestamp (in milliseconds since Unix epoch) and then feeds it into new Date() which uses it to create a Date object representing that time. .toGMTString() outputs the date formatted for the GMT timezone. To output it formatted in local time, use .toString() instead.
try this type:
var userDate = new Date();
var day = userDate.getDate();
var month = userDate.getMonth() + 1;
var year = userDate.getFullYear();
alert("Date Formate is :"+year+"-"+month + "-" + day);
In javascript you can use an external library like moment.js
var date = moment.unix(timestamp);
date.format("YYYY MM DD");
See detail about .format here https://momentjs.com/docs/#/displaying/format/

New date() returning next date instead of today's date

i am trying to convert a string into date type.i am giving the string value to new date().
but it's returning next day date instead of date which i am trying to convert.
var endDate = new Date("2017-03-23T23:59:59.000Z");
//end date value is now ------ Fri Mar 24 2017 05:29:59 GMT+0530 (India Standard Time).
Please suggest me how can get correct date in the format MM/DD/YYYY
This hack can help you,
var endDate = new Date("2017-03-23T23:59:59.000Z").toISOString();
it will give you,
"2017-03-23T23:59:59.000Z"
Further if you want to convert it to DD/MM/YYYY then you can use native javascript or lib like moment for that,
This simpile js will help to convert it to any format.
var endDate = new Date("2017-03-23T23:59:59.000Z").toISOString();
var d1 = endDate.split('T'); //spliting date from T
var d2 = d1[0].split('-'); //getting date part
console.log('yyyy/MM/dd', d2[0] + "/" + d2[1] + "/" + d2[2]) //YYYY/MM/DD
console.log("DD/MM/YYYY", d2[2] + "/" + d2[1] + "/" + d2[0])
jsfiddle link
if your time is in IST use below
var endDate = new Date("2017-03-23T23:59:59.00+0530");
If you check dates, you will see that your dates differs in 5h 30 mins, that is same as your date saying GMT +0530. Your original date has .000Z that is time zone of GMT +0.
Make sure you use same time zone when working with date.
Try using Date.UTC('your date')
JavaScript Date objects carry no timezone information. The only reason you saw a non-UTC date is that the browser chooses by default to display dates as local time in the console. If you don't care about the date object aligning with the exact instant in local time, you can use the following format function to turn it into MM/DD/YYYY format:
function format (date) {
var mm = ('0' + (date.getUTCMonth() + 1)).slice(-2)
var dd = ('0' + date.getUTCDate()).slice(-2)
var yyyy = date.getUTCFullYear()
return mm + '/' + dd + '/' + yyyy
}
var endDate = new Date("2017-03-23T23:59:59.000Z")
console.log(endDate.toISOString())
console.log(format(endDate))
(Credit to Ranj for posting an answer using Date#toISOString before mine.)
I have created the solution over here please find below link
https://www.w3schools.com/code/tryit.asp?filename=FD0YSGRMB59W

Parse date in javascript issues

I get such date in javascript
var val = "1960-05-15T20:00:00"
But if I do
var date = new Date(val);
The data I get is one day later:
1960-05-16 // I use this to obtain it: Ext.Date.format(new Date(val), 'm/d/Y')
Can you help me how to parse this date? and get correct date with 1960-05-15?
Your date format is ISO 8601 represented as the local time with an offset to UTC appended.
The Ext.Date singleton support this format with the c flag.
var parsedDate = Ext.Date.parse('1960-05-15T20:00:00', 'c');
var dateStr = Ext.Date.format(parsedDate, 'Y-m-d');
// "1960-05-15"
Have a look at the Sencha ExtJs 6.2.1 documentation Ext.Date for further informations.
You can use native JS to accomplish the output of the Date object in to this format yyyy-mm-dd
Like so:
var val = '1960-05-15T20:00:00';
var d = new Date(val);
var date = d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2);
console.log(date);
When you do
var a = new Date(someDate)
variable a contains date according to your local timezone.
If you want date in same format as you entered , use toISOString method
var a = (new Date(someDate)).toISOString()
My recommendation would be, you can only assume the timezone from where the date is coming from. If you know exactly where that date is coming from, a.k.a London, New York, Sidney, etc... then you can use momentjs to set the UTC offset
var val = "1960-05-15T20:00:00"
// these are equivalent
moment(val).utcOffset("+08:00");
moment(val).utcOffset(8);
moment(val).utcOffset(480);
So the OP has said they're in
Tbilisi, Georgia GMT + 4.00
so
moment(val).utcOffset("+04:00");

Creating a Javascript Date object by passing in a date? What is a dateString?

I am trying to figure out what the W3C website means by dateString.
http://www.w3schools.com/jsref/jsref_obj_date.asp
I am trying to do something like:
var _date = new Date("Mon Aug 12 2013 2:00 AM");
or even:
var _date = new Date("Mon, Aug 12 2013, 2:00 AM");
Is there a quick way of turning my string into a format that the date object likes?
Thank you
edit:
I suppose it expects the following:
var d = new Date()
d.toDateString()
"Tue Aug 13 2013"
Is it only that type of string?
The Javascript string-based Date constructor accepts strings in a format accepted by Date.parse().
These are date strings compliant with RFC-2822 or ISO-8601.
Use String in this format:
new Date('2013-08-13')
or
new Date('2013-08-13T10:51:00');
Here, this is how to use dateString as a parameter
var dateString = "08/12/2013";
var d = new Date(dateString);
dateString = d.getFullYear() + "/" + d.getMonth() + "/" + d.getDate();
document.write(dateString);
Remember month are stored at 0th index in javascript.

Categories

Resources