IOS Swift NSDate from String output GMT midnigth - nsdate

I want to store in a sqlite database timeintervalSince1970.
If I use this code:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
var initDate: NSDate = dateFormatter.dateFromString("23-03-2015 00:00")!
let timeInSeconds = initDate.timeintervalSince1970 // 1,427,324,400.0
When I pass timeInSeconds to NSDate:
let dateStore: NSDate = NSDate(timeIntervalSince1970: timeInSeconds)
If I print dateStore:
println(dateStore)
Output '2015-03-22 23:00:00 +0000'
timeInSeconds = 1427324400.0 -> '2015-03-22 23:00:00 +0000', but to store '2015-03-23 00:00:00 +0000' the interval should be 1427328000.0
I do not know how to get it.
When I use this code:
let cal2: NSCalendar = NSCalendar.currentCalendar()
cal2.timeZone = NSTimeZone(name: "Europe/Madrid")!
var timeZoneComps: NSDateComponents = NSDateComponents()
timeZoneComps.day = 23
timeZoneComps.month = 3
timeZoneComps.year = 2015
timeZoneComps.hour = 0
timeZoneComps.minute = 0
timeZoneComps.second = 0
var date1: NSDate = cal2.dateFromComponents(timeZoneComps)!
println(date1)
Output println: 2015-03-22 23:00:00 +0000
Any help, please?

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
let myDateMidnightLocalTime = dateFormatter.dateFromString("23-03-2015 00:00")! // Mar 23, 2015, 12:00 AM
let timeInSeconds = myDateMidnightLocalTime.timeIntervalSince1970 // 1,427,079,600.0
let dateStored = NSDate(timeIntervalSince1970: timeInSeconds) // Mar 23, 2015, 12:00 AM matches
dateStored.timeIntervalSince1970 // 1,427,079,600.0 matches

Related

How to convert String time to datetime which includes gmt

Time should be sent in this format
"2023-01-09T10:45:00.000+05:30"
and the String which i have to parse into datetime is only "10:00 AM"
i tried doing this
var GMTdateFormat = DateFormat('yyyy-MM-ddHH:mm:ss.000+05:30').format(
DateTime.parse(
(state as SlotRequestPopUpDataLoadedState)
.slotStartTimingList
.where((element) => element.isSelected == true)
.map((e) => e.name)
.toString(),
).toUtc(),
);
But it is not working
try this:
//input: 10:00 AM
final time = DateFormat('hh:mm a').parse("10:00 AM");
final year = DateTime.now().year;
final month = DateTime.now().month;
final day = DateTime.now().day;
final dateString = DateFormat('$year-$month-${day}THH:mm:ss.SSS+05:30').format(time);
print(dateString); //2023-1-9T10:00:00.000+05:30

How to convert 'HH:MM' to a particular GMT time on Python?

Suppose that you have a variable that stores the following time zone format as string type:
timezone = '(GMT -5:00)'
Now you have the following times, which were set in GMT -4:00 time and as string types:
time1 = '4:00' #am (GMT -4:00)
time2 = '9:00' #am (GMT -4:00)
How can be used the variable timezone to change the time1 and time2 values to its corresponding local times? that is:
time1 = '3:00' #am (GMT -5:00)
time2 = '8:00' #am (GMT -5:00)
Figured it out, it ain't that great but it's honest work:
import datetime
timezone = '(GMT -5:00)'
timezone = timezone.replace("(", "").replace("GMT ", "").replace(":","").replace(")", "")
gmt_hours = int(timezone[:2])
gmt_less_4_hours = -4
time_difference = abs(gmt_hours - gmt_less_4_hours)
time1 = "04:00" #am (GMT -4:00)
time1 = datetime.datetime.strptime(time1, "%H:%M")
time1 -= datetime.timedelta(hours=time_difference)
time1 = time1.strftime('%H:%M')
print(time1)
time2 = '9:00' #am (GMT -4:00)
time2 = datetime.datetime.strptime(time2, "%H:%M")
time2 -= datetime.timedelta(hours=time_difference)
time2 = time2.strftime('%H:%M')
print(time2)
Output:
03:00
08:00

find number of days for given month and year in nodejs

I am trying to get number of days for given month and year in node.js
npm i date-and-time is install in node
dailyCalibRptTempTbl(req){
return new Promise((resolve,reject) => {
let responseObj = {};
var str_date = req.body.date;
var year = str_date.split('-')[0];
var month = str_date.split('-')[1];
var day = this.getNumOfDays(year,month);
console.log(day);
})
}
getNumOfDays(y,m){
var days = date(y, m, 0).getDate();
return days;
}
expect then in 31 days for month 3 and year 2019
Use new Date as like below
function getNumOfDays(y, m) {
return new Date(y, m, 0).getDate();
}
Using Moment js It is very easy to find the number of days in a given month.
Suppose your date format is 2019-03-30
you want to know the number of days in 2019-03
const moment = require('moment')
moment('2019-03', 'YYYY-MM').daysInMonth()
For Number of days in a given year, Check if the given year is a leap year or not, if it is a leap year, number of days = 366, else 365.
let isLeapYear = moment([2019]).isLeapYear()
let numOfDaysInYear = 365
if(isLeapYear){
numOfDayInYear = 366
}

How to get current datetime with format Y-m-d H:M:S using node-datetime library of nodejs?

I'm using node-datetime library. I want to get current datetime with format such as Year-month-day hour-minute-second
ex : 2016-07-04 17:19:11
var dateTime = require('node-datetime');
var dt = dateTime.create();
dt.format('m/d/Y H:M:S');
console.log(new Date(dt.now()));
But my result such as:
Mon Jul 04 2016 17:19:11 GMT+0700 (SE Asia Standard Time)
See the docs for details on format:
Returns a formatted date time string.
Store the result of your call to dt.format and don't pass this to the Date constructor:
var dateTime = require('node-datetime');
var dt = dateTime.create();
var formatted = dt.format('Y-m-d H:M:S');
console.log(formatted);
[ Run the example above: https://replit.com/#SamGluck1/so-node-datetime ]
I have amended the format string from 'm/d/Y' to 'Y-m-d' as per your question.

Convert time in milliseconds to date format (YYYY-MM-DD) in Groovy

Is there a function to convert time in milliseconds to date format (YYYY-MM-DD) in Groovy?
I have a Groovy script which needs to compare to date values as follows:
for(i in order_lineitems)
{
if(i.startDate==order_submit_date)
{
matchedIds1 += i.salesOrderLineitemId+',';
}
}
Here i.startDate has time in milliseconds of the date format yyyy-mm-dd whereas order_submit_date has the time in milliseconds in the date format yyyy-MM-dd HH:mm:ss. I need to convert order_submit_date into this format yyyy-mm-dd within the if block itself.
I am new to the Groovy script and I need help here.
There was a small mistake in my code. I corrected it.
The if block should be as follows if (i.startDate == order_submit_date) and both are long values represented in millis.
Now I need to make sure the condition is right i.e. start date is equal to order submit date.
Here what is happening is :
i.startDate has the value 1452105000000 (Thu Jan 07 2016 00:00:00) which is been stored in the DB when a Sales Order is created
and order_submit_date has the value 1452158393097 (Thu Jan 07 2016 14:49:53) which is being genertaed on the flow when a user submits the Sales order for approvals in the UI.
Now since order_sbmit_date has both date and time the long value is different and am unable to satisfy the condition.
Hence now i have a question as to wether there a function in groovy which would convert my order_submit_date long value to Date(yyyy-mm-dd) format and then compare both the values so as to satisfy the if block.
You can compare your dates in millis like this:
Notice that solutions depend on timezone.
Groovy option:
def compare(def m1, def m2) {
def dateInMillis1 = new Date(m1)
def dateInMillis2 = new Date(m2)
dateInMillis1.clearTime() == dateInMillis2.clearTime()
}
Java option 1:
boolean compare1(long millis1, long millis2) {
Date dateFromMillis = new Date(millis1);
Date dateFromMillis2 = new Date(millis2);
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
sdf.format(dateFromMillis).equals(sdf.format(dateFromMillis2));
}
or you can use Calendar:
Java option 2:
boolean compare2(long m1, long m2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(m1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTimeInMillis(m2);
return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) &&
calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH) &&
calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
}
Your question is not clear that whether your dates are in string format or in milliseconds (long).
If dates are in string format like "2015-10-31"
You can use SimpleDateFormat for this.
import java.text.SimpleDateFormat
...
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd")
SimpleDateFormat dateTimeParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
for (i in order_lineitems) {
if (dateParser.parse(i.startDate) >= dateTimeParser.parse(order_submit_date)) {
matchedIds1 += i.salesOrderLineitemId+',';
}
}
If dates are in milliseconds:
for (i in order_lineitems) {
if (new Date(i.startDate.toString().toLong()) >= new Date(order_submit_date.toString().toLong())) {
matchedIds1 += i.salesOrderLineitemId+',';
}
}
Note: Capital Y and small y (similarly for m & h) matterns in terms of formatting so please be clear about the usage.
Actual Answer to the Question:
You don't need any of the above solution instead you can simply use the clearTime() method on the date like below:
for (i in order_lineitems) {
if (new Date(i.startDate) >= new Date(order_submit_date).clearTime()) {
matchedIds1 += i.salesOrderLineitemId+',';
}
}
The clearTime() method will simply remove the time part from your date i.e. will convert Thu Jan 07 2016 14:49:53 to Thu Jan 07 2016 00:00:00`
What are type for i.startDate and order_submit_date java.util.Date? or String?
And do you want use i.startDate and order_submit_date only to do compare?
-- updated --
ok, then maybe like folowing?
import java.text.SimpleDateFormat
String startDate = "2016-01-20"
String order_submit_date = "2016-01-20 12:34:56"
SimpleDateFormat formatDateWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd")
if (formatDate.parse(startDate) >= formatDateWithTime.parse(order_submit_date)) {
println "hehe"
} else {
println "hoho"
}
SimpleDateFormat#parse() returns java.util.Date.
Also you can compare with these.
You can also write like follows!
import java.text.SimpleDateFormat
SimpleDateFormat formatDateWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd")
def matchedIds1 = order_lineitems.findAll {
formatDate.parse(it.startDate) >= formatDateWithTime.parse(order_submit_date)
}.join(",")
Long(type) version
def matchedIds1 = order_lineitems.findAll {
new Date(it.startDate).clearTime() == new Date(order_submit_date).clearTime()
}.join(",")
Long(type) without clearTime version
String format = "yyyy-MM-dd 00:00:00"
SimpleDateFormat fillByZero = new SimpleDateFormat(format)
def matchedIds1 = order_lineitems.findAll {
Date a = new Date(it.startDate)
Date b = new Date(order_submit_date)
fillByZero.parse(a.format(format)) == fillByZero.parse(b.format(format))
}.join(",")

Resources