json datetime to javascript datetime gets me wrong date - javascript

I am trying to convert datetime from the server in the form of JSON to something I can use in HighChart but I keep getting the wrong day.
var json = {"lastMinute":"2013-05-06 15:46:00"}; // GMT
var lastMinute = json.lastMinute;
var a = lastMinute.split(' ');
var d = a[0].split('-');
var t = a[1].split(':');
var date = new Date(d[0],d[1],d[2],t[0],t[1],t[2]);
// NEED TO CONVERT TO LOCALTIME
this outputs: Thu Jun 06 2013 15:46:00 GMT-0700 (PDT)
can someone put my out of my misery and tell me what stupidly simple thing I'm doing wrong?

in js, months start with 0 instead of 1...
var json = {"lastMinute":"2013-05-06 15:46:00"}; // GMT
var lastMinute = json.lastMinute;
var a = lastMinute.split(' ');
var d = a[0].split('-');
var t = a[1].split(':');
var date = new Date(d[0],d[1]-1,d[2],t[0],t[1],t[2]);

You can use Datejs (https://code.google.com/p/datejs/wiki/APIDocumentation) library. It is very usefull and you have the metod parseExact:
Date.parseExact("10/15/2004", "M/d/yyyy");

For ultimate in parsing and formatting dates in JavaScript, use the moment.js library.
You can be explicit about UTC, and this works just fine in downlevel browsers.
var m = moment.utc('2013-05-06 15:46:00');
These values look like they are in ISO8601 format (without the T). So you should be ok with just the above code. But if you want to be even more precise, you could do:
var m = moment.utc('2013-05-06 15:46:00', 'YYYY-MM-DD HH:mm:ss');
I would recommend keeping it as a moment for as long as possible. Their formatting is superb. But if you need it back as a javascript date, just do:
var date = m.toDate();

Related

How to grab standard date from DateTime object in Javascript

My date is as followed 2020-05-13T18:00:00+01:00
I am trying to grab the time, but in standard format. In this case, it'll be 06:00:00 pm
May I have some guidance on how to achieve this?
I've tried the following.
vm.training.startDate = '2020-05-13T18:00:00+01:00`'
var start = new Date(vm.training.startDate)
var locale = start.toLocaleTimeString(); // Produced 1:00:00 PM (not the value I'm looking for)
var test = start.getTime(); // produced 1589389200000
var test1 = start.toTimeString(); // produced 13:00:00 GMT-0400 (Eastern Daylight Time)
var test3 = moment(vm.training.startDate, 'MM-DD-YYYY hh:mm A') // moment date object
This one is quite close but still slightly off
var test4 = moment(vm.training.endDate, 'HH:mm').format('hh:mm:ss a')// produced `08:30:00 pm`
Any tips would be greatly appreciated
Use momentjs format to convert a date string to the respective format by specifying the format string.
Docs: https://momentjs.com/docs/#/parsing/string-formats/
console.log(
moment("2020-05-13T18:00:00+01:00", "YYYY-MM-YYYY HH:mm").format("hh:mm:ss a")
);
<script src="https://momentjs.com/downloads/moment.js"></script>
You can pass the timezone option when calling toLocaleTimeString() method:
var options = { timeZone: 'Europe/London'};
var d = new Date('2020-05-13T18:00:00+01:00');
var n = d.toLocaleTimeString('en-UK', options);
console.log(n)

What does my date time get converted into from ASP.Net MVC to Javascript

In my html file I'm passing an array of objects with a date time to javascript like this
<script>
var TimerEvents = #Html.Raw(Json.Encode(Model.PendingTimerEvents));
</script>
my 'TimerEvents' has an EventTime property that when I read in Javascript looks like this
"/Date(1521617700000)/"
and I want to get this value, whatever it is, into a Javascript Date() object.
like this
var countDownDate = new Date(date here).getTime();
What is that format, and how would I do this?
the value you get is a milisecond representation of the date, I think the count starts at 1/1/1970.
Anyway here is a solution for formatting it:
Converting milliseconds to a date (jQuery/JavaScript)
Assuming that Model.PendingTimerEvents is a DateTime, you could just do:
var TimerDate = new Date(#Model.PendingTimerEvents.Year, #Model.PendingTimerEvents.Month, #Model.PendingTimerEvents.Day, #Model.PendingTimerEvents.Hour, #Model.PendingTimerEvents.Minute, #Model.PendingTimerEvents.Second);
You can extract the date with regex if you need to:
<script>
var TimerEvents = #Html.Raw(Json.Encode(Model.PendingTimerEvents)); //"/Date(1521617700000)/"
var dateString = TimerEvents.match(/\d+/)[0] // "1521617700000"
var date = new Date(+dateString); //convert to number
console.log(date); // Wed Mar 21 2018 08:35:00 GMT+0100 (Mitteleuropäische Zeit)
</script>

Date and time based json element using javascript

I have a json response like this :
{
"NO_INSPECTION": "55",
"NO_SURAT": "00055",
"DATE_OF_DESCRIPTION": "2015-12-21 03:08:24"
}
How can I convert the data in "DATE_OF_DESCRIPTION" Into date and time. Date should be dd-mm-yyy format and time should be in HH:mm format. (A sample value of DATE_OF_DESCRIPTION is 2015-12-21 03:08:24)
I have tried new Date(response.DATE_OF_DESCRIPTION); but no success. How can I achieve this?
Without the use of other libraries and assuming the output will always be zero-padded and the same length, I would do this:
var response = {
DATE_OF_DESCRIPTION: "2015-12-21 03:08:24"
}
var raw = response.DATE_OF_DESCRIPTION;
var datePart = raw.split(' ')[0];
var timePart = raw.split(' ')[1];
var year = datePart.substring(0, 4);
var month = datePart.substring(5, 7);
var day = datePart.substring(8, 10);
var hours = timePart.substring(0, 2);
var minutes = timePart.substring(3, 5);
// NOTE: Month is 0 indexed
var date = new Date(year, month - 1, day);
var dateTime = new Date(year, month - 1, day, hours, minutes);
console.log(date);
console.log(dateTime);
This gives the output
Mon Dec 21 2015 00:00:00 GMT+1000 (E. Australia Standard Time)
Mon Dec 21 2015 03:08:00 GMT+1000 (E. Australia Standard Time)
(I'm from Australia, so your timezone will vary)
JavaScript has a fixed date format and you can change it, thus the Date object won't help you this time. As I see it, you want to split that date, so it's pretty easy if you provide it in this format "dd-mm-yyy HH:mm":
response.DATE_OF_DESCRIPTION = response.DATE_OF_DESCRIPTION.split(" "); // date and time are separated by an space
var date = response.DATE_OF_DESCRIPTION[0];
var time = response.DATE_OF_DESCRIPTION[1];
BTW, if you want to parse a date in a specified format, why don't you use any library for that? Many of them are almost as reliable and fast as native methods. Give them a try ;)
You could also format the date, so it fits the JS specs but, why reinvent the wheel? Libraries will do this for you and you'll get optimal cross-browser results!
I've googled "javascript date parsing library" and this is what I've found:
http://momentjs.com/ <--- I think that's what you're looking for!

How To Convert String ' dd/mm/yy hh:MM:ss ' to Date in javascript?

I have Done this
var d='dd/mm/yy hh:MM:ss';
var d1=d.split(" ");
var date=d1[0].split("/");
var time=d1[1].split(":");
var dd=date[0];
var mm=date[1]-1;
var yy=date[2];
var hh=time[0];
var min=time[1];
var ss=time[2];
var fromdt= new Date("20"+yy,mm-1,dd,hh,min,ss);
Is there Any way to do it using JQuery OR JavaScript?
If you are looking for alternatives in jquery or Javascript , then you can go with Moment.js,where you can Parse, Validate, Manipulate, and Display dates in JavaScript.
example:
var date= moment("06/06/2015 11:11:11").format('DD-MMM-YYYY');
This will work regardless of timezone for the format dd/mm/yyy hh:mm:ss only. It also does not rely on third party packages:
let dtStr = "12/03/2010 09:55:35"
console.log(strToDate(dtStr)); // Fri Mar 12 2010 09:55:35
function strToDate(dtStr) {
if (!dtStr) return null
let dateParts = dtStr.split("/");
let timeParts = dateParts[2].split(" ")[1].split(":");
dateParts[2] = dateParts[2].split(" ")[0];
// month is 0-based, that's why we need dataParts[1] - 1
return dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0], timeParts[0], timeParts[1], timeParts[2]);
}
How about Date.parse()?
new Date( Date.parse("05/12/05 11:11:11") );
// Thu May 12 2005 11:11:11 GMT+0200 (CEST)
The output produced is in local timezone and will differ in browsers in different timezones.
We can convert any local date format to datetime datatype using moment js.
Syntax:
moment('<local date value>','<local date format>').format('<expected convert format>')
Example:
moment('26/05/1986 00:00', 'DD/MM/YYYY HH:mm').format("MM/DD/YYYY HH:mm");
then the output will be 05/26/1986 00:00
Cheers
Date#parse should be able to parse that if you split on a string. Id also recommend looking into the npm package moment for date manipulation
From your code it seems that you are trying to convert string into date and also you are trying to fetch previous month. If yes then you can reconstruct your code as below:
Date.prototype.SubtractMonth = function(numberOfMonths) {
var d = this;
d.setMonth(d.getMonth() - numberOfMonths);
return d;
}
$(document).ready(function() {
var dateString='2015-06-17T18:30:12';
var d = new Date(dateString);
alert(d.SubtractMonth(1));
});

Add Number of months to a Date in a text field

function addDays(){
var myDate =document.getElementById('treatdate');
var numberOfDaysToAdd = document.getElementById('resultdays');
var tset = numberOfDaysToAdd.value;
var result1 = myDate.value.addMonths(parseInt(tset));
var pldate= moment(result1).format('YYYY-MM-DD');
return pldate; }
'treatdate' is an id for a treatment date which is pulled from my database. Thanks in advance.
You can always use moment.js library for Date manipulations. http://momentjs.com/
For your problem you can do the following.
function addDays(){
var datefrmDb = $('#treatdate').val();
var monthstoadd= $('#resultdays').val();
var new_date = (moment(datefrmDb, "YYYY-MM-DD").add('months', monthstoadd)).format("YYYY-MM-DD");
return new_date;
}
If your date format is yyyy-MM-dd
var myDate = new Date(document.getElementById('treatdate').value);
this will a date and time.
Example:
var dd = new Date("2014-02-02 11:11:11")
console log
Sun Feb 02 2014 11:11:11 GMT+0000 (GMT Standard Time)
See if this snippet can help you understand how to manipulate dates. To change/add the months to a Date() object you can use the setMonth() method.
numberOfMonthsToAdd = 5; // the number of months that you want to add
date = new Date(); // creating a Date object
date.setMonth(numberOfMonthsToAdd); // adding the number of months
Note that you may add numbers beyond 12 - the object handles the date, and jumps to the next year.

Categories

Resources